我有一个django表单,我需要从数据库中填充下拉字段
我的表格看起来
prod_cat = forms.ModelChoiceField(
queryset=ProductCategory.objects.order_by('prod_cat', 'cat_desc').values_list('prod_cat', 'cat_desc').distinct())
当我运行将其渲染到html下拉菜单时,它看起来像这样,
{'product_category':'Electronics','product':'Laptops'}
我只想显示这些值
Electronics Laptops
答案 0 :(得分:0)
要以自定义方式显示数据,您必须继承ModelChoiceField
并覆盖label_from_instance
:
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return '%s %s' %(obj.product_category, obj.product)
使用MyModelChoiceField
代替ModelChoiceField