擅长:python、mysql、java
<p>我找到了一个解决方案,它的工作方式,我希望它不违反干燥原则。不是很干净,但我想必须这样做。</p>
<p>根据<a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#choices" rel="noreferrer">the documentation</a>选择不一定是元组:</p>
<blockquote>
<p>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.</p>
</blockquote>
<p>所以我现在的解决办法是:</p>
<pre><code>COMPETITION_TYPE_CHOICES = [
(1, 'Olympic Games'),
(2, 'ISU Championships'),
(3, 'Grand Prix Series'),
]
COMP_TYPE_CHOICES_AND_EMPTY = [('','All')] + COMPETITION_TYPE_CHOICES
</code></pre>
<p>然后:</p>
<pre><code>class CompetitionSearchForm(forms.Form):
name = forms.CharField(required=False)
type = forms.ChoiceField(choices=COMP_TYPE_CHOICES_AND_EMPTY, required=False)
</code></pre>
<p>模型保持原样。</p>