有可能在Django中返回一个选项的显示名称吗



因此,当您为表单/模型进行选择时,您需要执行以下操作:

EXP_CHOICES = (
('1ST','First'),
('2ND','Second'),
.......
('XXX','YYY'),
) # where XXX is the value stored in the database and YYY is what you see in a form.

这也适用于查询,因此当您有上述选择并选择一个时,对模型进行查询,它会返回"1ST"/"2ND"/"XXX"。

但是如果您想显示YYY呢?因此,我们知道"1ST"是"第一",但我们希望让它成为用户可读的。

有没有一种方法可以访问EXP_CHOICES并写出与之相关的YYY,或者您必须生成if&其他/选择器与类似

{% if data.chosen == '1ST'%}
First
{% elif ... %}
...
{% endif %}

您使用.get_fieldname_display(…)[Django doc],所以如果模型字段是chosen,那么它就是get_chosen_display:

{{data.get_chosen_display}}

相关内容

最新更新