我需要在现有的 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)
我只是想知道是否有更好的解决方案。