使用枚举作为选择来获取选择显示值 [英] Get choices display value using enum as choices
问题描述
我有一个Django模型,其中使用了choices参数.对于选择,我使用的是Python枚举.现在,我想在模板中显示选择显示值.我知道有 .get_fieldname_display
,但是在这种情况下,它只是返回键而不是显示值.
I have a Django model in which I'm using the choices parameter. For the choices, I'm using a Python Enum. Now I want to display the choices display value in a template. I know there's .get_fieldname_display
but it just returns the key instead of the display value in this case.
型号:
class LocalTitle(models.Model):
type = models.CharField(max_length=8, choices=[(tag, tag.value) for tag in LocalTitleCodes])
title = models.CharField(max_length=255)
枚举:
class LocalTitleCodes(Enum):
title_00 = 'Japanese'
title_01 = 'English'
title_02 = 'French'
因此,在我的情况下,如果我在模板中执行 title.get_type_display
,它将返回 title_00
而不是 Japanese
.如何获得显示值?
So in my case, if I do title.get_type_display
in my template it returns title_00
and not Japanese
. How can I get the display value?
推荐答案
我认为问题更多是 tag
不会 not 映射到 title__00
,但是是 LocalTitleCodes
对象.
I think the problem is more that tag
does not map to title__00
, but to a LocalTitleCodes
object.
您应该使用:
class LocalTitle(models.Model):
type = models.CharField(
max_length=8,
choices=[(tag.name, tag.value) for tag in LocalTitleCodes]
)
title = models.CharField(max_length=255)
由于Django无法找到相应的值,因此它回退到存储在数据库中的值.
Since Django thus could not find a the corresponding value, it fallsback on the value stored in the database.
因为:
>>> [(tag, tag.value) for tag in LocalTitleCodes]
[(<LocalTitleCodes.title_00: 'Japanese'>, 'Japanese'), (<LocalTitleCodes.title_01: 'English'>, 'English'), (<LocalTitleCodes.title_02: 'French'>, 'French')]
>>> [(tag.name, tag.value) for tag in LocalTitleCodes]
[('title_00', 'Japanese'), ('title_01', 'English'), ('title_02', 'French')]
这篇关于使用枚举作为选择来获取选择显示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!