How to change Django MultipleChoiceField to display multiple data from multiple tables and use specific value

62 views Asked by At

I have 3 relational Django database tables and i want to display data in 'name_en' column in all the tables as labels, and 'id' in city table as value in Django MultipleChoiceField

| Example Table Structure |

Table 1 (province):
| id       | name_en    |name_ta    |
| -------- | ---------- |---------- |
|1         | Western    | -         |
|2         | Central    | -         |

Table 2 (district):
| id       | ForeignKey  | Name_en     |Name_ta |
| -------- | ----------- | ----------- |------- |
|1         | 2           | Kandy       | -      |
|2         | 1           | Colombo     | -      |

Table 3 (city):
| id       | ForeignKey  | Name_en    |Name_ta    |
| -------- | ----------- | ---------- |---------- |
|1         | 1           | Uduwela    | -         |
|2         | 2           | Homagama   |-          |

I want to display MultipleChoiceField in this format

<select>
<option value='1(city id)'>Western,Colombo,Homagama</option>
</select>
1

There are 1 answers

0
Alexander Schillemans On BEST ANSWER

You could do something like this:

class CityForm(forms.Form):
    
    cities = forms.MultipleChoiceField(
        choices=[]
    )

    def __init__(self, *args, **kwargs):
        
        cities = City.objects.all()
        cities_list = []
        for city in cities:
            cities_list.append([city.id, '{0}, {1}, {2}'.format(
                city.name_en,
                city.district.name_en,
                city.province.name_en
            )])
        
        super().__init__(*args, **kwargs)
        self.fields['cities'].choices = cities_list

You loop over all the cities, get their district, and then get the district's province. Assuming a city can only have one district and a district can only have one province.