问题描述
我将在我的数据库中保存有关比赛的数据.我希望能够按特定条件搜索比赛 - 特别是比赛类型.
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)
问题
我希望 ChoiceField 中的选择小部件显示一个空标签,但我没有找到.对此的任何帮助将不胜感激:)
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.
根据文档 选择没有成为一个元组:
According to the documentation choices don't have to be a tuple:
最后,请注意选择可以是任何可迭代对象——不一定是列表或元组.这使您可以构建动态选择.但是如果你发现你自己的黑客选择动态的,你可能会更好使用适当的数据库表外键.选择是为了变化不大的静态数据,如果有的话.
所以我目前的解决方案是:
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 不显示空标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!