Django Model Ordering Procedure

How to access an ordered list of model fields? Since model_instance._meta.fields returns fields without m2m, but in admin mode, the fields are ordered exactly the same as they are defined in the class. (for example, change the form on the admin site)?

+6
source share
1 answer

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 can use fields + many_to_many directly, since both of them are already in the order of declaration.

Update

If you prefer to use operator.attrgetter() instead of lambda , that's fine, the performance difference is trivial. But attrgetter not guaranteed 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 
+6
source

Source: https://habr.com/ru/post/918766/


All Articles