1

我需要在现有的 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_labelempty_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) 

我只是想知道是否有更好的解决方案。

4

1 回答 1

0

有一个选项empty_label可用于为空选项选项设置自定义值。

hardness = forms.ModelChoiceField(
    queryset=Description.objects.filter(variable="hardness", paradigm='206209').values_list('dvalue', flat=True).distinct().order_by('dvalue'),
    empty_label='Not applicable', #for instance
    required=False
)

遵循文档:

请注意,如果需要 ModelChoiceField 并且具有默认初始值,则不会创建空选项(无论 empty_label 的值如何)。

于 2013-06-26T22:01:14.237 回答