Custom Model Manager

A snippet showing how to extend Django model managers with custom methods.


# models.py

from django.db import models

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_published=True)

class Article(models.Model):
    title = models.CharField(max_length=200)
    is_published = models.BooleanField(default=False)

    objects = models.Manager()  # default manager
    published = PublishedManager()  # custom manager

    def __str__(self):
        return self.title
  

# Django Shell

>>> from blog.models import Article
>>> Article.objects.create(title='Draft Post', is_published=False)
>>> Article.objects.create(title='Live Post', is_published=True)
>>> Article.objects.all()
<QuerySet [<Article: Draft Post>, <Article: Live Post>]>
>>> Article.published.all()
<QuerySet [<Article: Live Post>]>
  
Explanation:
  • A custom manager lets you add extra query logic for models, beyond the default objects manager.
  • You can override get_queryset() or define custom methods (like active()).
  • Using managers keeps query logic organized and reusable across your project.
  • Always keep the default objects manager if you add a custom one, unless you want to replace it completely.
  • Category Models & ORM
  • Total Views 368
  • Last Modified 19 November, 2025
  • Tags #models #managers #orm #queries
Previous snippet
Auto Timestamp Fields
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.