Django中models定义的choices字典使用get_FooName_display()在页面中显示值
问题
在django的models.py 中,我们定义了一些choices的元组,类似一些字典值,一般都是下拉框或者单多选框,例如 0对应男 1对应女等等
看下例子:
class Area(models.Model):
Area_Level = (
(0, u'全国'),
(1, u'省、直辖市'),
(2, u'市、直辖市区'),
(3, u'区、县等'),
)
areaname = models.CharField(max_length=30,unique=True, verbose_name='区域名称')
code = models.CharField(max_length=20,blank=True, default="", verbose_name='区域代码')
parentid = models.IntegerField(verbose_name='父级id', null=True)
level = models.IntegerField(choices=Area_Level,verbose_name='层级', null=True)
在页面中有个table要把表中的字段显示出来,如果数据库中存储的是0就显示 全国, 1就显示省、直辖市 类似:
名称 代码 层级 上级地区 操作
全国 全国(0) 删除
北京 bj 省、直辖市(1) 全国 删除
我们可以自己定义一个函数来判断使用,但方法确实比较low,那么django中有没有这种方法可以让我们直接使用呢?
我们先来看下Django官方的解释:
Documentation for "choices" should mention "get_FOO_display"
Description
The documentation for the choices
attribute on model fields mentions that choices
should be a tuple of 2-tuples, including an actual value and a human-readable name, but documentation on how to retrieve the human-readable name of the selected choice from an instance of the model lives elsewhere, in the database API documentation, under the unintuitive name of get_FOO_display
. This hinders a new user of Django trying to understand how best to make use of choices
.
At the very least, the model documentation should include, under choices
, a link to the get_FOO_display
entry in the DB documentation for an explanation of how to get the human-readable name back out of a model instance. Ideally, we'd do that and come up with better titles for the sections on the various get_FOO_display
/get_next_by_FOO
/etc. methods.
在页面上我们只要这么写就可以直接把字典的值显示出来了
{{ obj.get_level_display }}({{ obj.level }})
obj.get_字段名称_display 。
models中的choices字段
由元素为2-tuples的序列(list或者tuple)作为字段的choices。2-tuple的第一个元素存储在数据库中,第二个元素可由get_FOO_display方法得到。
>>>p=Person(name='Sam',gender=1)
>>>p.save()
>>>p.gender
1
>>>p.get_gender_display()
u'Male'