Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django listing model fields in order

Tags:

django

model

I am trying to list a model fields on the order of the model creation. I tried ._meta.get_all_field_names() but it seems to return a random dictionnary. How can I list an ordered list of fields in a view ?

I mean : I have a model like :

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)

And I want to list the fields in order : concerning / title / first_name / family_name/ etc...

like image 930
Romain Jouin Avatar asked Nov 27 '25 12:11

Romain Jouin


1 Answers

Django's built-in functions may help:

from django.forms.models import fields_for_model

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

returns

['concerning', 'title', 'first_name', ...]
like image 188
Selcuk Avatar answered Nov 30 '25 06:11

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!