Django ModelChoiceField Distributed Area

I have a drop-down list that is populated with a filtered list of objects from the Parameters model. The drop-down list currently displays the names of each option. How can I make another attribute from the same table be displayed?

self.fields['name'] = forms.ModelChoiceField(queryset = Options.objects.filter(option_type = s), label = field_label, required=False) 

A quick example: the names of cars are displayed in the drop-down list: "Camero, Nissan, Honda" How can I make it display the color of each car ("black, black, white"). Note that color is also a field in the Option table.

+3
source share
1 answer

You can override label_from_instance in ModelChoiceField after creating it.

 self.fields['name'] = forms.ModelChoiceField(queryset = Options.objects.filter(option_type = s), label = field_label, required=False) self.fields['name'].label_from_instance = lambda obj: "{0} {1}".format(obj.name, obj.color) 

Update based on comment only to display color once:

 class MyModelChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): super(MyModelChoiceField, self).__init__(self, *args, **kwargs) self.shown_colors = [] def label_from_instance(self, obj): if obj.color not in self.shown_colors: self.shown_colors.append(obj.color) return "{0} {1}".format(obj.name, obj.color) else: return obj.name self.fields['name'] = MyModelChoiceField(queryset = Options.objects.filter(option_type = s), label = field_label, required=False) 
+3
source

Source: https://habr.com/ru/post/944267/


All Articles