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
source share