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'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM