Skip to content

Maximizing Your App’s Performance with Custom Model Manager in Django

how to Custom Model Manager in Django

Django custom model managers allow you to define custom querysets for a model. This can be useful for creating specialized querysets that can be reused throughout your application.

How to create a custom model manager with the example?

For example, let’s say we have a model for “BlogPost” and want to create a custom manager that returns only published blog posts. We would first create a custom manager class that inherits from django’s built-in “Manager” class and overrides the “get_queryset” method. django model manager get queryset

from django.db import models

class PublishedManager(models.Manager):
    # filter published
    def get_queryset(self):
        return super().get_queryset().filter(status='published')
Django model manager best practices:

Next, we would add the custom manager as a class attribute on our “BlogPost” model:

class BlogPost(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    status = models.CharField(max_length=10)
    
    objects = models.Manager() # The default manager
    published = PublishedManager() # Our custom manager

With this setup, we can now use the custom manager to retrieve only published blog posts like this:

BlogPost.published.all()

And we can still use the default manager to retrieve all blog posts :

BlogPost.objects.all()

You can chain the filters and other related functionalities to the manager like,

BlogPost.published.filter(title__icontains='django').exclude(content__icontains='bidyut')

You can also add custom methods to your custom manager class, which can be useful for encapsulating complex queries or other business logic.

Here is another creative example of a custom model manager django. Let’s say you want to create a custom manager called ActiveManager, which returns only active user profiles.

What is django model manager get_queryset?
from django.db import models

class ActiveManager(models.Manager):
    #filter active
    def get_queryset(self):
        return super().get_queryset().filter(is_active=True)

and apply that to your UserProfile model,

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    profile_picture = models.ImageField(upload_to='profile_pictures/', default='default.jpg')
    
    objects = models.Manager() # The default manager
    active = ActiveManager() # Our custom manager

This way, you can use UserProfile.active.all() to get all the active user profiles only.

Some of the most commonly used django model manager methods:
  • all(): Returns a queryset containing all objects for the model.
  • filter(**kwargs): Returns a queryset containing objects that match the given lookup parameters.
  • exclude(**kwargs): Returns a queryset containing objects that do not match the given lookup parameters.
  • get(**kwargs): Returns a single object that matches the given lookup parameters, or raises a DoesNotExist exception if no match is found.
  • get_or_create(**kwargs): Returns a tuple containing an object that matches the given lookup parameters, and a boolean indicating whether the object was created or retrieved from the database.
  • create(**kwargs): Creates and saves a new object for the model, with the given field values.
  • update_or_create(defaults=None, **kwargs): creates or updates an object, returns tuple (obj, created)
  • bulk_create(objs, batch_size=None): Creates a number of objects in bulk, in a single database query.
  • count(): Returns the number of objects in the database for the model.
  • first(): Returns the first object for the model.
  • last(): Returns the last object for the model.
  • earliest(field_name=None): Returns the earliest object by date, date time or any field which follows the date based
  • latest(field_name=None): Returns the latest object by date, date time or any field which follows the date based

FAQ:

What is django manager vs queryset?

Managers provide a way to define and retrieve querysets for a specific model, and querysets represent database queries and allow you to retrieve, update, or delete objects from the database.

The Short Note:

In conclusion, Django custom model managers provide a powerful and flexible way to manage the database operations for your models. They allow you to create custom querysets, encapsulate complex queries and business logic, and improve the performance of your web applications.

Related tutorial: How to create custom model fields in Django

Leave a Reply

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