Django按顺序列出模型字段

时间:2015-02-18 21:13:37

标签: django model

我正在尝试按照模型创建的顺序列出模型字段。我试过._meta.get_all_field_names(),但它似乎返回一个随机的词典。如何在视图中列出有序的字段列表?

我的意思是:我有一个类似的模型:

class UserInfo(models.Model):
    concerning                  = models.ForeignKey(User)
    title                       = models.CharField(max_length=100,              choices=zip(titles, titles))
    first_name                  = models.CharField(max_length=100  )
    family_name                 = models.CharField(max_length=100, )
    gender                      = models.CharField(max_length=1 ,               choices=(("f", "female"), ("m",  "male")))
    nationality                 = models.CharField(max_length=100,  blank=True, choices=(countries))
    email2                      = models.EmailField()
    Telephone                   = models.CharField(max_length=30)
    webpage                     = models.URLField(max_length=100,   blank=True)

我想按顺序列出字段:related / title / first_name / family_name / etc ...

1 个答案:

答案 0 :(得分:3)

Django的内置功能可能有所帮助:

from django.forms.models import fields_for_model

...
fields = fields_for_model(UserInfo).keys()

返回

['concerning', 'title', 'first_name', ...]