【问题标题】:ModelChoiceField Concatenate two fields in one field - DjangoModelChoiceField 在一个字段中连接两个字段 - Django
【发布时间】:2018-04-11 09:59:53
【问题描述】:

您好,我不知道如何将两个字段模型转换为一个“自定义”以提出一个唯一字段(将 ('fieldA','fieldB') 传递给 ('fieldA fieldB')。

我正在尝试构建一个内部模型函数,但没有异常结果...

models.py

class Referencebank(models.Model):
    idtable1 = models.AutoField(db_column='idtable1', primary_key=True)
    genus = models.CharField(max_length=45, blank=True, null=True)
    species = models.CharField(max_length=45, blank=True, null=True)
    subspecies = models.CharField(max_length=45, blank=True, null=True)


    def getScientifName(self):
        return str(self.genus) + " " + str(self.species);


    class Meta:
        managed = False
        db_table = 'table1'

forms.py

class ScientifNameForm(forms.Form):

    for ref in Referencebank.objects.all():

        queryset = ref.getScientifName();
        print("\n queryset")


    scientifName = forms.ModelChoiceField(queryset=Referencebank.objects.values_list('genus','species').order_by('genus').distinct(),
                                                   empty_label="(Nothing)",
                                                   required=False,
                                                   help_text="Select the bacteria",label='Scientific Name')

在 forms.py 中,for 循环正确执行我希望在模型选择字段中显示的结果

我想要这样的东西

        scientifName = forms.ModelChoiceField(queryset=Referencebank.objects.values_list('scientificName').order_by('scientificN').distinct(),
                                                   empty_label="(Nothing)",
                                                   required=False,
                                                   help_text="Select the bacteria",label='Scientific Name')

【问题讨论】:

  • 在模型本身上定义__str__ 并使用queryset=Referencebank.objects.all() 会更容易吗?

标签: python django python-3.x django-models django-forms


【解决方案1】:

听起来你需要重写ModelChoiceFieldlabel_to_instance方法。

from django import forms

class ScientificNameChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.getScientifName()

然后在表单中使用您的自定义字段。

class ScientifNameForm(forms.Form):
    scientifName = ScientificNameChoiceField(
        queryset=Referencebank.objects.all(),
        help_text="Select the bacteria",
        label='Scientific Name',
    )

【讨论】:

  • 感谢您的回答。我认为您的意思是 ScientificNameChoiceField 而不是 class ScientifNameForm(forms.Form) 中的 ReferencebankChoiceField。我的回答有这个错误AttributeError: 'ScientificNameChoiceField' object has no attribute 'getScientifName' 也许我不太了解 django 中有关模型/表单的一些提示。
  • 我已经解决了几个问题。名称由您决定,但应保持一致。在label_from_instance 中,应该是obj.getScientifName() 而不是self.getScientifName()
  • 完美答案 =)
猜你喜欢
  • 2020-06-25
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2013-08-21
  • 2013-03-26
  • 1970-01-01
  • 2014-06-15
  • 2021-08-06
相关资源
最近更新 更多