There is no doubt that the built-in user 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 django user model. In such a scenario, we can extend the Django User Model using various methods. Such extended models are called Django Custom User Models. In this tutorial, we will be learning to extend the Django 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. The Django Proxy user model only changes the behaviour of an already existing user model from which it inherits. This method is useful if you want to add some methods to your existing user 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 Django Custom User Model - Person, which inherits the Django 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 Custom User Model.