Django Django

What's the difference between a custom Manager and a custom QuerySet?

Dima Ноя 15, 2026

Short Answer

A Manager is the entry point attached to the model class; a QuerySet is the chainable thing it hands out. Shipment.objects is a Manager instance, and Shipment.objects.all() is the QuerySet it produced. That difference decides where a custom method belongs: a method defined on the Manager can only ever be the first call, because everything after it is a QuerySet and knows nothing about the Manager. A method defined on a QuerySet subclass composes anywhere in a chain, and QuerySet.as_manager() puts it on the Manager as well — which is why the default advice is to write the method on the QuerySet and let the Manager borrow it.


How It Works

objects is not a queryset and not a collection of rows. It is an instance of Manager attached to the model class, reachable as Shipment.objects and deliberately unreachable as shipment.objects — a single row is not a gateway to the whole table, so Django raises rather than letting the attribute resolve on an instance.

A Manager's job is to produce querysets. Every row-returning method on it starts by calling get_queryset(), which builds a brand new QuerySet for the model. Model.objects.all() is essentially that call, and Model.objects.filter(…) is get_queryset().filter(…). Each access builds a fresh object, which is what stops one caller's filters from leaking into another's.

Chaining is where the two part company. QuerySet methods return querysets, so they compose indefinitely: filter().exclude().order_by(). A Manager method returns whatever you wrote it to return, and the moment it hands back a QuerySet, the Manager is out of the picture — the QuerySet class has never heard of your method. So a custom Manager method works at the start of an expression and nowhere else.

QuerySet.as_manager() and Manager.from_queryset() resolve this by building a Manager whose methods are copied from your QuerySet subclass. The same method then exists in both places: callable directly on the manager, and available mid-chain because it genuinely lives on the queryset class. This is why "put it on the QuerySet" is the default answer, and why Manager-only methods are reserved for things that do not return querysets at all, like a factory that creates a row.

Overriding get_queryset() changes the starting point for everything that Manager does — count(), get(), filter(), iteration. That is the mechanism behind a default-filtered manager, and also its hazard: the rows are not deleted, merely invisible through that entrance. The first manager declared on a model also becomes _default_manager, which Django itself reaches for in places you do not control, so a filtering manager declared first quietly changes behaviour well beyond your own calls.


Seeing It Run

These steps share a fixture. Create depot/models.py and bootstrap.py as shown in the first step, plus an empty depot/__init__.py, then replace main.py for each later step. Run with:

python3 main.py

What objects actually is

The model declares three managers so later steps can compare them. This step only looks at the first.

# depot/models.py
from django.db import models


class ShipmentQuerySet(models.QuerySet):
    def booked(self):
        return self.filter(status="booked")


class BookingManager(models.Manager):
    def booked(self):
        return self.filter(status="booked")


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


class Shipment(models.Model):
    reference = models.CharField(max_length=20)
    status = models.CharField(max_length=20)
    archived = models.BooleanField(default=False)

    objects = BookingManager()
    records = ShipmentQuerySet.as_manager()
    active = ActiveManager()


# bootstrap.py
import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    INSTALLED_APPS=["depot"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    DEFAULT_AUTO_FIELD="django.db.models.AutoField",
    USE_TZ=False,
)
django.setup()

from django.db import connection

from depot.models import Shipment


def seed():
    with connection.schema_editor() as editor:
        editor.create_model(Shipment)
    Shipment.objects.create(reference="SHP-4471", status="booked")
    Shipment.objects.create(reference="SHP-4408", status="in-transit")
    Shipment.objects.create(reference="SHP-3157", status="booked", archived=True)
    connection.queries_log.clear()


# main.py
from bootstrap import Shipment, seed

seed()

print("Shipment.objects is a  :", type(Shipment.objects).__name__)
print("and .all() returns a   :", type(Shipment.objects.all()).__name__)
print("a fresh one every call :", Shipment.objects.all() is not Shipment.objects.all())

try:
    Shipment(reference="SHP-0001").objects
except AttributeError as exc:
    print("on an instance         :", exc)


Shipment.objects is a  : BookingManager
and .all() returns a   : QuerySet
a fresh one every call : True
on an instance         : Manager isn't accessible via Shipment instances


Two different classes, one line apart. objects is the BookingManager instance declared on the model; all() is the QuerySet it built. Each call to all() produces a separate object, so two callers filtering from Shipment.objects never interfere. The AttributeError is deliberate rather than incidental — Django blocks the attribute on instances so that shipment.objects.filter(...) cannot be mistaken for something scoped to that row.

Try it: Add the same two questions for the second manager at the end: print(type(Shipment.records).__name__) and print(type(Shipment.records.all()).__name__). records was created with ShipmentQuerySet.as_manager(); which classes do you expect to see? You get ManagerFromShipmentQuerySet and ShipmentQuerySet. as_manager() generated a manager class that copies the queryset's methods, and that manager returns your custom queryset rather than the base QuerySet, which is why its methods survive chaining in the next step.


Where the method lives decides where it can be called

Replace main.py. booked() is defined twice in the fixture — once on BookingManager, once on ShipmentQuerySet — and the two behave differently in a chain.

# main.py
from bootstrap import Shipment, seed

seed()

print("manager method            :", [s.reference for s in Shipment.objects.booked()])
try:
    Shipment.objects.filter(archived=False).booked()
except AttributeError as exc:
    print("chained after filter()    :", exc)

print("queryset method           :", [s.reference for s in Shipment.records.booked()])
print("chained after filter()    :", [s.reference for s in Shipment.records.filter(archived=False).booked()])
print("and in the other order    :", [s.reference for s in Shipment.records.booked().filter(archived=False)])


manager method            : ['SHP-4471', 'SHP-3157']
chained after filter()    : 'QuerySet' object has no attribute 'booked'
queryset method           : ['SHP-4471', 'SHP-3157']
chained after filter()    : ['SHP-4471']
and in the other order    : ['SHP-4471']


Both booked() implementations do the same filtering, and only one of them survives a chain. Shipment.objects.filter(...) returns a plain QuerySet, which has no booked attribute — the method exists on the Manager, and the Manager is no longer involved. records was built with ShipmentQuerySet.as_manager(), so booked() lives on the queryset class itself: callable straight off the manager, usable after filter(), and usable before it. Composability in either order is the property you are buying.


Overriding get_queryset() moves the starting point

Replace main.py. ActiveManager filters out archived rows before anything else runs.

# main.py
from bootstrap import Shipment, seed

seed()

print("objects.count():", Shipment.objects.count())
print("active.count() :", Shipment.active.count())

print("objects.get('SHP-3157') ->", Shipment.objects.get(reference="SHP-3157").reference)
try:
    Shipment.active.get(reference="SHP-3157")
except Shipment.DoesNotExist:
    print("active.get('SHP-3157')  -> DoesNotExist, though the row is there")


objects.count(): 3
active.count() : 2
objects.get('SHP-3157') -> SHP-3157
active.get('SHP-3157')  -> DoesNotExist, though the row is there


One override changes every method on that manager, because they all begin at get_queryset(). count() reports two, and get() raises DoesNotExist for a row that plainly exists and is returned by objects.get() one line above. That is the soft-delete pattern working exactly as designed, and it is also the trap: the exception says the object is not there, when the truth is that this entrance cannot see it. Keep an unfiltered manager available so the full table stays reachable.

Try it: Add print(Shipment.active.filter(archived=True).count()). An archived row exists in the table and you are asking for it explicitly; what number appears? 0. Your filter does not replace get_queryset(), it is added to it: the SQL asks for archived to be false and true at the same time, a condition no row can satisfy. A manager that filters in get_queryset() cannot be widened from outside, only bypassed through another manager.


Edge Cases and Gotchas

  • Declaring any manager removes the automatic objects. A model with only records = ShipmentQuerySet.as_manager() has no objects attribute at all. Declare objects = models.Manager() explicitly if you still want it.
  • The first manager declared becomes _default_manager. Django reaches for it in the admin, in dumpdata, and elsewhere, so a filtering manager in first position changes behaviour far outside your own code. Declare the unfiltered one first.
  • A filtered default reaches into reverse relations but not forward ones. carrier.shipments is built from the related model's _default_manager, so archived shipments disappear there too. Forward access is the opposite: shipment.carrier goes through _base_manager and still loads an archived carrier. The same filter applies in one direction and not the other.
  • Use from_queryset() when you need both. BookingManager.from_queryset(ShipmentQuerySet) produces a manager carrying the queryset's chainable methods plus any manager-only methods you defined.
  • Some methods genuinely belong on the Manager. Anything that does not return a queryset — a factory like create_from_payload() — gains nothing from being chainable and reads better on the manager.

Summary

A Manager is the model's entry point and a QuerySet is the chainable result it produces. Methods on the Manager can only start an expression; methods on a QuerySet subclass compose anywhere, and as_manager() exposes them at both ends.

  • Model.objects is a Manager instance on the class, not a queryset, and is deliberately inaccessible from an instance.
  • Every row-returning manager method begins at get_queryset(), which builds a fresh QuerySet, so chains never share state.
  • A method defined on a Manager is unavailable after any queryset call; define it on a QuerySet subclass and use as_manager() to get both.
  • Overriding get_queryset() re-bases every method on that manager, which is how default filtering works and why get() can raise DoesNotExist for a row that exists.
  • The first manager declared is _default_manager and is used by Django internally, so declare an unfiltered manager first.

Чтобы получить доступ к облачной лаборатории, необходимо войти в систему.

Войти