Sitemap

Django proxy models

1 min readDec 11, 2022

--

Press enter or click to view image in full size

A proxy model gives you more control on the models. Suppose, an User model consists of all kind of users(superuser, staff and common users[neither superuser and staff]). When you apply filter on the model for only common users, You have to explicitly specify conditions on queryset to exclude superuser and staff

User.objects.exclude(Q(is_superuser=True) & Q(is_staff=True))

So, Proxy models eliminates this barrier and gives you flexibility to apply more conditions on resultant queryset.

from django.contrib.auth.models import User
from django.db import models
class ProxyUserManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).exclude(Q(is_superuser=True) & Q(is_staff=True))
class ProxyUser(User):
objects = ProxyUserManager()
class Meta:
proxy = True

Now you can simply query ProxyUser instead of User model. which only gives you common users, which works as normal model but the only different is queryset result

ProxyUser.objects.all()

Get Dharma Teja K’s stories in your inbox

Join Medium for free to get updates from this writer.

The advantages of using proxy models are

  1. It won’t create any new table in database
  2. Can only inherit from one model
  3. You can perform every ORM operation on this model as usual
  4. This is not only for fetching results. You can perform all kind of database actions

Thanks for reading. If you like my article please share it with your friends.

You can find more about me here

LinkedIn: https://www.linkedin.com/in/dharma-teja-547572132/
GitHub: https://github.com/teja-official

--

--

Dharma Teja K
Dharma Teja K

Written by Dharma Teja K

Great learnings gives you better opportunities to grow