Adding Custom Models Manager In Django

Adding Custom Models Manager In Django

Here we will get some hands dirty on django managerA django manager is object of class Manager.  A Manager is a interface through which we make queries in django.

Create Django Models

Let us take example of users model which can be defined as:

from django.db import models

class Users(models.Model):
    name = models.CharField(max_length=50, null=True)
    Source = models.CharField(max_length=15)
    source_facebook = FacebookManager() # facebook user manager
    source_instagram = InstagramManager() # instagram user manager

Now, for this models we want to implement a manager which gives count of no of users in diffrent source. Here i have used two manager for same purpose first is source_facebook  which is django default manager and another is source_instagram  which is our custom manager. 

Create Django Manager

So lets get started for facebook manager we will write code as:

class FacebookManager(models.Manager):
    """Facebook Specific Manager"""
    def get_queryset(self):
        return super().get_queryset().filter(source='facebook')

Here i have created on class FacebookManager to get all facebook source users in queryset and overwrite get_queryset method and count method for users whoose source is facebook.  

class InstagramManager(models.Manager):
    """Instagram Specific Manager"""
    def get_queryset(self):
        return super().get_queryset().filter(source='instagram')

In same way i did for instagram users. Now, both source_facebook  and source_instagram  is a queryset so we can use any method on that objects like  Users.source_facebook.count()  this returns a total users whose source is facebook and in same way Users.source_instagram.count()  returns total count of users whose source is instagram. You can use any queryset methods on this objects like filter(), exclude(), get()etc. For more information you can check this django documentation.

Leave a Comment