← Back to Django, page 2

django-0032 · Medium mid

What are custom managers and custom QuerySet methods in Django, and why use QuerySet.as_manager()?

A manager is the interface for table-level queries (Model.objects). Adding methods to a custom QuerySet class and exposing it with QuerySet.as_manager() or Manager.from_queryset() gives chainable, reusable filters such as Book.objects.available().by_author(...). Overriding get_queryset() on a manager changes the default rows it returns, which is how soft-delete filters are often built.

Full answer

Book.objects is a Manager. It hands out QuerySets. When the same filter appears in many views, for example "books that are in stock and not lost", put it on the model layer rather than repeating filter(copies__gt=0, lost=False) everywhere.

Two places to add logic:

  • Custom QuerySet methods: chainable, because each returns a QuerySet.
  • Custom Manager methods: table-level helpers, such as a create_student() that sets defaults.

The usual pattern puts methods on a QuerySet and exposes them through the manager:

python
class BookQuerySet(models.QuerySet):
    def available(self):
        return self.filter(copies__gt=0, lost=False)
    def by_author(self, name):
        return self.filter(author__iexact=name)

class Book(models.Model):
    ...
    objects = BookQuerySet.as_manager()

Now Book.objects.available().by_author("Ruskin Bond") chains in any order.

Manager.from_queryset(BookQuerySet) is used when you also need custom manager-only methods or want to override get_queryset().

Changing default rows: a manager whose get_queryset() filters out soft-deleted records hides them everywhere. Keep a second, unfiltered manager (all_objects = models.Manager()), and know that Django uses Meta.base_manager_name (the plain base manager by default) for related object access, so a default-manager filter does not apply to loan.book.

Rules:

  • The first manager defined on the model is the default manager unless Meta.default_manager_name says otherwise.
  • Keep QuerySet methods about selecting rows. Complex business workflows (issue a book, send a notice) fit better in service functions.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection


class BookQuerySet(models.QuerySet):
    def available(self):
        return self.filter(copies__gt=0, lost=False)

    def by_author(self, name):
        return self.filter(author__iexact=name)


class ActiveManager(models.Manager.from_queryset(BookQuerySet)):
    def get_queryset(self):
        return super().get_queryset().filter(deleted=False)


class Book(models.Model):
    title = models.CharField(max_length=60)
    author = models.CharField(max_length=40)
    copies = models.PositiveIntegerField(default=1)
    lost = models.BooleanField(default=False)
    deleted = models.BooleanField(default=False)

    objects = ActiveManager()          # default: hides soft-deleted rows
    all_objects = models.Manager()     # everything

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Book)

Book.all_objects.bulk_create([
    Book(title="The Blue Umbrella", author="Ruskin Bond", copies=2),
    Book(title="Rusty Runs Away", author="Ruskin Bond", copies=0),
    Book(title="The Room on the Roof", author="Ruskin Bond", lost=True),
    Book(title="Delhi Is Not Far", author="Ruskin Bond", deleted=True),
    Book(title="Malgudi Days", author="R. K. Narayan"),
])

print(list(Book.objects.available().by_author("ruskin bond").values_list("title", flat=True)))
print(list(Book.objects.by_author("Ruskin Bond").available().values_list("title", flat=True)))
print(Book.objects.count(), Book.all_objects.count())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['The Blue Umbrella'] ['The Blue Umbrella'] 4 5

Key points

  • Managers create QuerySets; QuerySet methods chain
  • QuerySet.as_manager() exposes chainable methods on objects
  • Override get_queryset() to change default rows
  • Keep an unfiltered manager alongside a filtered one
  • Related access uses the base manager

Common mistakes

  • Putting reusable filters on the manager only, so they cannot be chained
  • Filtering the default manager and being surprised that related access still shows hidden rows
  • Accidentally making a filtered manager the default and breaking the admin or dumpdata
  • Moving whole business workflows into QuerySet methods

Follow-ups

  • How would you build soft delete across the whole project?
  • What is the base manager used for?
  • How do custom managers behave in migrations (use_in_migrations)?

Tips

  • Show a chain in both orders to prove the methods compose
  • Mention the default manager rule
  • Bring up soft delete as a real use case