擅长:python、mysql、java
<p>如果在包含值到名称映射的字段上定义<code>choices</code>,则将在该字段的任何<code>ModelForm</code>中呈现一个选择字段,并在模型上生成一个方法,以获取所选值的显示名称<a href="https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.get_FOO_display" rel="nofollow noreferrer">^{<cd3>}</a></p>
<pre><code>class Ingredient(models.Model):
COST_BY_CHOICES = (
(1, 'Units'),
(2, 'Kilograms'),
(3, 'Litters'),
)
cost_by = models.IntegerField(choices=COST_BY_CHOICES)
</code></pre>
<p>像这样使用</p>
<pre><code>ingredient = Ingredient(cost_by=1)
print(ingredient.get_cost_by_display())
</code></pre>