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'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值