Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply Django model Meta options to models that I did not write?

Tags:

python

django

I want to apply the "ordering" Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to modify the User model?

like image 867
hekevintran Avatar asked Apr 06 '09 02:04

hekevintran


1 Answers

This is how the Django manual recommends you do it:

You could also use a proxy model to define a different default ordering on a model. The standard User model has no ordering defined on it (intentionally; sorting is expensive and we don't want to do it all the time when we fetch users). You might want to regularly order by the username attribute when you use the proxy. This is easy:

class OrderedUser(User):
    class Meta:
        ordering = ["username"]
        proxy = True

Now normal User queries will be unorderd and OrderedUser queries will be ordered by username.

Note that for this to work you will need to have a trunk checkout of Django as it is fairly new.

If you don't have access to it, you will need to get rid of the proxy part and implement it that way, which can get cumbersome. Check out this article on how to accomplish this.

like image 179
Paolo Bergantino Avatar answered Oct 04 '22 02:10

Paolo Bergantino