在Django模板中访问PositiveSmallIntegerField的选择值。

问题描述 投票:0回答:1

我有一个这样的模型。

class SomeModeL(Model):
    MODEL_TYPE = (
        (0, 'Type1'), 
        (1, 'Type2'), 
        (2, 'Type3')
        )
    model_type = PositiveSmallIntegerField(choices=MODEL_TYPE)

现在,我把模型的一个实例传入上下文,想访问model_type,特别是String,比如 "Type1

所以,在模板中,我这样做。{{ some_model.model_type }} 但这返回的是整数,不是字符串。我怎样才能得到字符串呢?

python django
1个回答
3
投票

你可以使用 get_fieldname_display [Django-doc] 替换为 fieldname 与你想要 "翻译 "的字段名称在其文本表示中)来获得相应的值,所以。

{{ some_model.get_model_type_display }}
© www.soinside.com 2019 - 2024. All rights reserved.