使用元组时ChoiceField不会显示空标签 [英] ChoiceField doesn't display an empty label when using a tuple

查看:83
本文介绍了使用元组时ChoiceField不会显示空标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在数据库中保留有关比赛的数据。我希望能够按特定条件(尤其是比赛类型)搜索比赛。

I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.

竞争类型保存在元组中。一个简短的例子:

Competition types are kept in a tuple. A slightly shortened example:

COMPETITION_TYPE_CHOICES = (
    (1, 'Olympic Games'),
    (2, 'ISU Championships'),
    (3, 'Grand Prix Series'),
)

这些在模型中的用法如下(再次-这是模型的简化/简化版本):

These are used in the model like so (again - this is a shortened/simplified version of the model):

class Competition(models.Model):
    name = models.CharField(max_length=256)
    type = models.IntegerField(choices=COMPETITION_TYPE_CHOICES) 



搜索表单



我不希望搜索表单中的字段为必填项,因此表单的定义如下:

The search form

I don't want the fields to be required in the search form, so the form is defined like this:

class CompetitionSearchForm(forms.Form):
    name = forms.CharField(required=False)
    type = forms.ChoiceField(choices=COMPETITION_TYPE_CHOICES,required=False)



< h2>问题

我希望ChoiceField中的select小部件显示一个空实验室埃尔,但我没有。任何对此的帮助将不胜感激:)

The problem

I'd like the select widget in ChoiceField to display an empty label, but I don't get one. Any help with this would be much appreciated :)

推荐答案

我已经找到了一种解决方案,该解决方案可以实现我希望的解决方案违反了DRY原则。

I've found a solution that works the way I want it to without violating the DRY principle. Not very clean, but it'll have to do I suppose.

根据文档选择不必是元组:


最后,请注意,选择可以是任何
迭代对象-不一定是
列表或元组。这使您可以动态构造
选择。但是,如果您发现自己选择
是动态的
,则最好使用带有
ForeignKey的适当数据库表来使
更好。选择是针对不变的
静态数据,如果有,则为

Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.

因此,解决方案我现在要使用的是:

So the solution I'm going with for the moment is:

COMPETITION_TYPE_CHOICES = [
     (1, 'Olympic Games'),
     (2, 'ISU Championships'),
     (3, 'Grand Prix Series'),
]

COMP_TYPE_CHOICES_AND_EMPTY = [('','All')] + COMPETITION_TYPE_CHOICES

然后:

class CompetitionSearchForm(forms.Form):
    name = forms.CharField(required=False)
    type = forms.ChoiceField(choices=COMP_TYPE_CHOICES_AND_EMPTY, required=False)

模型保持不变。

这篇关于使用元组时ChoiceField不会显示空标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆