Django ModelChoiceField下拉框定制人口 [英] Django ModelChoiceField drop down box custom population
问题描述
我有一个下拉框,由一个模型选项中的过滤的对象列表填充。目前,下拉列表显示每个选项的名称。如何从同一个表中显示另一个属性?
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)
快速示例:下拉框目前显示汽车的名称:Camero,Nissan,Honda
我该如何让它显示每辆车的颜色(黑色,黑色,白色)。请注意,颜色也是选项表中的一个字段。
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.
推荐答案
您可以覆盖 label_from_instance
在 ModelChoiceField
在构建后。
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)
根据注释更新仅显示一次颜色: / p>
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)
这篇关于Django ModelChoiceField下拉框定制人口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!