django ModelChoiceField在内容上显示对象

kse8i1jr  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(135)

我如何改变我的代码来显示内容而不是对象?
forms.py:

unit_set = AnalysisVariableUnit.objects.all()
for unit in AnalysisVariableUnit.objects.all():
    print(unit.__dict__)

class AnalyysimuuttujaForm(forms.Form):
    technical_name = forms.CharField(required=False,
                                     widget=forms.TextInput(
                                        attrs={
                                            'class':'readonly_able tn'
                                            }
                                        ))
    decimals = forms.ChoiceField(choices=CHOICES_DS)
    decimals_format = forms.ChoiceField(choices=CHOICES_DS)
    units = forms.ModelChoiceField(
            required=False,
            widget=forms.Select,
            queryset=unit_set,
        )

这一结果是:

{'_state': <django.db.models.base.ModelState object at 0x7f2038ea51d0>, 'id': 1, 'contents': 'indeksipisteluku'}
{'_state': <django.db.models.base.ModelState object at 0x7f2038ea5240>, 'id': 2, 'contents': '%'}

我想在下拉菜单中选择'indeksipisteluku'和'%',现在显示:

k10s72fa

k10s72fa1#

AnalysisVariableUnit object (...)是Django的__str__模型的默认输出。
将描述性__str__添加到模型中:

def __str__(self):
    return str(self.contents)
jexiocij

jexiocij2#

重写model类中的str()函数,正确自定义下拉列表。

class AnalysisVariableUnit(models.Model):
    # your data variables
    
    def __str__(self):
        return self.contents # or any thing you want to show in dropdown

相关问题