Create custom object manager in django admin

In django, generally you can query on a model like:

Products.objects.all()

Or if you want to apply a condition, you can do like:

Products.objects.filter(is_active=True).all()

Let’s assume that you want active products list on different places. So you will use Products.objects.filter(is_active=True).all() to get the list of active products. Now if your active product condition changed to is_active=True, is_launched=True then you have to change the filter() condition everywhere.

To overcome this issue, you can create a custom object manager where you can create definitions to manage your object or in simple words, we can say that you can create custom definitions to hold your filter conditions. These filter conditions can be applied on the objects. Consider custom manager shown below and add it in your models.py file.

class CustomObjectManager(models.Manager):

   def active(self):
       return self.filter(is_active=True)

   def active_launched(self):
       return self.filter(is_active=True, is_launched=True)

You can use custom object manager in you model class by assigning it to Model.objects

#apply custom object manager
objects = CustomObjectManager()

Now your model class will look like:

class Products(models.Model):

   def __str__(self):
       return self.name

   name = models.CharField(max_length=100)
   code = models.SlugField(blank=True)
   description = models.TextField()
   outline = models.TextField()
   is_launched = models.BooleanField(default=False)
   is_active = models.BooleanField(default=False)

   #apply custom object manager
   objects = CustomObjectManager()

In views.py file, where you want to query for active products, you can do as:

Products.objects.active().all()

It will query for all products where is_active=True

To query for all products where is_active=True and is_launched=True, you can do:

Products.objects.active_launched().all()

You can apply more filters on object managers. For example if you want active and launched products with name “abc”, you do can this as:

Products.objects.active_launched().filter(name="abc").all()

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares