3

I have a dropdown box that is being populated by a filtered list of objects from a model "Options". Currently, the dropdown list displays the names of each option. How would I get it to display another attribute from the same table?

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

Quick example: drop down box currently displays the names of the cars: "Camero, Nissan, Honda" How would I get it to display the color of each car ("black, black, white"). Note that the color is also a field in the Option table.

JohnnyCash
  • 1,231
  • 6
  • 17
  • 28

1 Answers1

3

You can override the label_from_instance on the ModelChoiceField after it's constructed.

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 to only show the 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)
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
  • can you do it so it only displays unique instances? so for example, instead of showing the color twice, just show it once? – JohnnyCash Mar 11 '12 at 18:26