Django ModelChoiceField drop down box custom population

拜拜、爱过 提交于 2020-01-13 18:15:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!