Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model field order

How can I access the ordered list of model fields? Because model_instance._meta.fields returns fields without m2m, but in admin view the fields order exactly same as they are defined in class. (like edit form on admin site) ?

like image 439
Andrey Baryshnikov Avatar asked Jun 22 '12 14:06

Andrey Baryshnikov


1 Answers

Try

sorted(model_instance._meta.fields + model_instance._meta.many_to_many,
       key=lambda x:x.creation_counter)

If M2M fields are defined after normal fields, you could use fields + many_to_many directly since both of them are already in the declaration ordering.

update

If you prefer to use operator.attrgetter() instead of lambda, it's OK, the performance difference is trivial. But attrgetter is not guranteed to be faster:

In[1]: from django.contrib.auth.models import User
In[2]: fields = User._meta.fields + User._meta.many_to_many
In[3]: %timeit sorted(fields, key=lambda x:x.creation_counter)
100000 loops, best of 3: 6.47 us per loop

In[4]: from operator import attrgetter
In[5]: %timeit sorted(fields, key=attrgetter('creation_counter'))
100000 loops, best of 3: 9.17 us per loop

In[6]: ag=attrgetter('creation_counter')
In[7]: %timeit sorted(fields, key=ag)
100000 loops, best of 3: 8.68 us per loop
like image 74
okm Avatar answered Oct 06 '22 00:10

okm