博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django中models定义的choices字典使用get_FooName_display()在页面中显示值
阅读量:4578 次
发布时间:2019-06-09

本文共 1994 字,大约阅读时间需要 6 分钟。

问题

在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.gender1>>>p.get_gender_display()u'Male'

转载于:https://www.cnblogs.com/ccorz/p/6362297.html

你可能感兴趣的文章
201621123042《java程序设计》第十三次作业
查看>>
CAST 和 CONVERT
查看>>
tr:even 与tr:odd
查看>>
Visual Studio2008 代码度量
查看>>
sql CONVERT函数应用
查看>>
洛谷 P3927 Factorial
查看>>
Wince 6.0获取设备的分辨率 自动设置窗体位置
查看>>
git
查看>>
[转帖]一文读懂 HTTP/2
查看>>
sql游标模板
查看>>
php将图片保存到mysql数据库及从数据库中读取图片的方法源码 转
查看>>
javascript面向对象习题答案
查看>>
使用use操作符导入/使用别名
查看>>
Python元祖
查看>>
Tornado的基本知识
查看>>
A1058. 芯片测试
查看>>
谷歌在线测试题
查看>>
20步打造最安全的Nginx Web服务器
查看>>
swfupload 上传控件的配置
查看>>
定制序列
查看>>