Udit Vashisht
Author: Udit Vashisht


How to extend Django User model using a proxy model?

  • Aug. 7, 2019, 12:22 p.m.
  • 2 minutes read
  • 36 Views
How to extend Django User model using a proxy model?

There is no doubt that the built-in authentication system of Django is quite good and caters the common use cases. But sometimes, we do not have our needs met with out-of-the-box defaults. In such a scenario, we can extend the User Model using various methods. In this tutorial, we will be learning to extend the User Model using a Proxy Model.

How to extend a Django User Model using a Proxy Model?

This method does not add any extra fields to our User model, it only changes the behaviour of an already existing model from which it inherits. This method is useful if you want to add some methods to your existing model or change the ordering etc. The database schema is not changed in this method.

You will need to add the following code in your models.py


from django.contrib.auth.models import User
from .managers import PersonManager

class Person(User):
    objects = PersonManager()

    class Meta:
        proxy = True
        ordering = ('first_name', )

    def custom_method(self):
        pass

In th above example, we have created a proxy model Person, which inherits the User model, by adding the following property in Meta class:

proxy = True

Then we have changed the ordering by first_name. You must note that though User.objects.all() and Person.objects.all() will call the same database but they will differ in behaviour vis-a-vis the later query will sort the result on the basis of first name.

Such kind of ordering comes handy in blog sites, where you need to show the newest blog post at the top. The same can be implemented as under:-

ordering = ("-updated")

Lastly, in custom_method() you can add some methods to your user model.



Related Posts

Best way to start a Django project (with Github Integration)
By Udit Vashisht | 3 months, 1 week ago

There are dozens of ways, which developers use to start their Django projects. Possibly, none of them would be a wrong way, but in this post we will be telling you a way which is very helpful and suitable not only in development but also in production (deployment). Not only ...

Read More
How to Extend Django User model using AbstractUser?
By Udit Vashisht | 3 months, 1 week ago

Even if the default Django User Model caters to all of your needs, it is highly recommended to use a Custom User Model. Django’s official documentation recommends so. Now there are two ways to create a Custom User Model:-

  1. By extending AbstractBaseUser
  2. By extending ...

    Read More
Search