DEV Community

Cover image for Custom Model Managers In Django
Vengat
Vengat

Posted on

Custom Model Managers In Django

Custom Model Managers In Django
A manager is an interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application, objects is the default manager of every model that retrieves all objects in the database.

However, one model can have multiple model managers, we can also build our own custom model managers by extending the base manager class.

Creating Custom Model Managers
`class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
active = models.BooleanField(default=False)

def __str__(self):
    return self.title`
Enter fullscreen mode Exit fullscreen mode

objects is the default model manager for every model, therefore Post.objects.all() will return all post objects.

The objects method is capable of doing all basic **QuerySets **then why would we need a custom model manager?

Why would we need Custom Model Manager

To add extra Manager methods.
To modify the initial QuerySet the Manager returns.
Let’s create a model manager to retrieve all the published posts.

Using the objects manager published posts can be retrieved with the following query.

Lets create some dummy data using Django Shell,

>>  Post.objects.filter(active=True) Out: <QuerySet [<Post: Fourth Post>, <Post: First post>]>

>> <QuerySet [<Post: Fourth Post>, <Post: First post>]>
Enter fullscreen mode Exit fullscreen mode

We will build a custom model manager called publish to retrieve the published posts.

class PublishManager(models.Manager):
    def get_queryset(self):
        return super(PublishManager, self).get_queryset().filter(active=True)
Enter fullscreen mode Exit fullscreen mode
class Post(models.Model):
    .. our fields

    objects = models.Manager()  # The default manager.
    publish = PublishManager()  # Our custom manager.

    def __str__(self):
        return self.title

Enter fullscreen mode Exit fullscreen mode

Now we can retrieve posts with the custom model manager as follows.

>> Post.published.all()   
>> <QuerySet [<Post: First post>, <Post: Fourth Post>]>

>> Post.objects.filter(active= True)     
>> <QuerySet [<Post: First post>, <Post: Fourth Post>]>
Enter fullscreen mode Exit fullscreen mode

Hope this would help you to understand the basic idea about custom model manager.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay