ModelChoiceField在一个字段中连接两个字段 - Django

时间:2018-04-11 09:59:53

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

您好我不知道将两个字段模型转换为一个'custom'以提出一个唯一字段(pass('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循环正确执行我想要在modelchoicefield中显示的结果

我想要那样的东西

        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')

1 个答案:

答案 0 :(得分: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',
    )