【发布时间】:2013-06-26 21:39:48
【问题描述】:
我需要将现有 valuelistqueryset 中的空选择值添加到我的 Django 类似表单中的以下选择字段到modelchoicefield("-------------")。谁能帮我解决这个问题?
hardness = forms.ModelChoiceField(queryset=Description.objects.filter(variable="hardness", paradigm='206209').values_list('dvalue', flat=True).distinct().order_by('dvalue'))
@jghyllebert 感谢您的回复。但在这种情况下,我需要将模型选择字段转换为选择字段。我需要choicefield 的解决方案。对不起,如果我不清楚。我在选择字段中尝试了empty_label 和empty_value,但表单出错了。
rimplan = forms.ChoiceField(
required=False,
empty_value = '---',
choices=Description.objects.filter(
variable="rimplan",
paradigm='206209').values_list(
'dvalue',
flat=True).distinct().order_by('dvalue'))
因此,我实施了这个解决方案,效果很好。
EXTSURCOLOR_DESCRIPTIONS = Description.objects.filter(
variable="exteriorsurfacecolor",
paradigm='206209')
EXTSURCOLOR_CHOICES = [('', '---')]
EXTSURCOLOR_CHOICES.extend(
EXTSURCOLOR_DESCRIPTIONS.values_list(
"dvalue",
"dvalue").distinct().order_by('dvalue'))
exteriorsurfacecolor = forms.ChoiceField(choices = EXTSURCOLOR_CHOICES)
我只是想知道是否有更好的解决方案。
【问题讨论】:
-
如果您设置了不适合您的
required=False,是否会显示空值?您不能将其直接插入查询集中,但它会将其添加到为该字段提供的选项中。
标签: django django-forms choicefield