DalinDad
DalinDad

Reputation: 103

ModelChoiceField Concatenate two fields in one field - Django

Hi i dont know the way to transform two fields model into one 'custom' to propose a unique field (pass ('fieldA','fieldB') to ('fieldA fieldB').

I am trying to build an inner model function but without excepted result...

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

In forms.py, the for loop execute correctly the result that i want display in modelchoicefield

I want something like that

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

Upvotes: 0

Views: 1945

Answers (1)

Alasdair
Alasdair

Reputation: 308959

It sounds like you need to override the label_to_instance method of ModelChoiceField.

from django import forms

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

Then use your custom field in your form.

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

Upvotes: 1

Related Questions