问题
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.
回答1:
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)
来源:https://stackoverflow.com/questions/9657344/django-modelchoicefield-drop-down-box-custom-population