我需要在現有的valueelistqueryset中爲我的Django similat形式下的choicefield添加空的選擇值到modelchoicefield("-------------")
。誰能幫我這個?需要添加空的選擇現有的價值觀查詢django choicefield
hardness = forms.ModelChoiceField(queryset=Description.objects.filter(variable="hardness", paradigm='206209').values_list('dvalue', flat=True).distinct().order_by('dvalue'))
@jghyllebert感謝您的回覆。但在這種情況下,我需要將modelchoicefield轉換爲choicefield。我需要choicefield的解決方案。對不起,如果我不清楚它。我在選擇字段中嘗試了empty_label和empty_value,但表單出錯。 (需要= False,empty_value ='---',選擇= Description.objects.filter(變量=「rimplan」,範式='206209')。values_list('dvalue',flat = True).distinct()。order_by('dvalue'))
因此,我已經實現了這個工作非常好的解決方案。
EXTSURCOLOR_DESCRIPTIONS = Description.objects.filter(可變= 「exteriorsurfacecolor」,範式= '206209')EXTSURCOLOR_CHOICES = [( '', '---')] EXTSURCOLOR_CHOICES.extend(EXTSURCOLOR_DESCRIPTIONS.values_list( 「dvalue」 (選項= EXTSURCOLOR_CHOICES)
我只是想知道是否有更好的解決方案。
如果設置了「required = False」,那麼顯示的空值是否存在?你不能從字面上將它插入到查詢集中,但它會將它添加到爲該字段提供的選擇中。 –