ModelChoiceField在一个字段Djang中连接两个字段

2024-09-29 17:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我不知道如何将两个字段模型转换为一个“自定义”字段,从而提出一个唯一的字段(pass('fieldA','fieldB')to('fieldA fieldB')。在

我试图建立一个内部模型函数,但没有例外的结果。。。在

在模型.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'

在表单.py在

^{pr2}$

在表单.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')

Tags: py模型selftruemodelsnulllengthmax
1条回答
网友
1楼 · 发布于 2024-09-29 17:21:56

听起来您需要重写^{}label_to_instance方法。在

from django import forms

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

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

^{pr2}$

相关问题 更多 >

    热门问题