Django 6.1.3

7.1 QuerySets and laziness

Chaining, cloning, and managers

How do managers forward queryset methods, what does QuerySet._clone copy vs. share, and when does Django disable cloning in place?

When you write "Story.objects.published().for_desk('metro').order_by('id')", you are calling a method on a Manager, getting back a "StoryQuerySet", and then chaining two more methods onto it — all without sending a single SQL statement. Open django/db/models/manager.py and django/db/models/query.py to see how Django wires those two classes together.

How BaseManager.from_queryset builds Manager

Look at line 176 of django/db/models/manager.py — the entire definition of Django’s default Manager class is two lines:

class Manager(BaseManager.from_queryset(QuerySet)):
    pass

Now read BaseManager.from_queryset and BaseManager._get_queryset_methods:

  1. It inspects every function defined on the queryset subclass via inspect.getmembers(..., predicate=inspect.isfunction).
  2. It skips any method already defined on cls, any private method starting with "_" (unless explicitly marked queryset_only = False, such as _insert and _update), and any public method marked queryset_only = True (such as QuerySet.delete and QuerySet.as_manager — which is why "Story.objects.delete()" raises AttributeError to prevent accidentally wiping an entire table!).
  3. For every remaining method, it generates a forwarding wrapper (getattr(self.get_queryset(), name)(*args, **kwargs)) and calls type(...) to synthesize a new subclass named "ManagerFromStoryQuerySet".
  4. When our newsroom’s "Story" declares "objects = StoryQuerySet.as_manager()", QuerySet.as_manager simply invokes BaseManager.from_queryset on Manager and stamps _built_with_as_manager = True so BaseManager.deconstruct can serialize it cleanly into migrations!

And look at the revealing comment on BaseManager.all:

def all(self):
    # We can't proxy this method through the `QuerySet` like we do for the
    # rest of the `QuerySet` methods. This is because `QuerySet.all()`
    # works by creating a "copy" of the current queryset and in making said
    # copy, all the cached `prefetch_related` lookups are lost.
    return self.get_queryset()

That is why "story.corrections.all()" hits the prefetch cache while "story.corrections.filter(...)" misses it: BaseManager.all returns the already-cached queryset straight from the related manager’s get_queryset() without cloning!

Finally, remember ManagerDescriptor: BaseManager.contribute_to_class attaches a descriptor that returns the manager from Options.managers_map on class access ("Story.objects") and raises AttributeError("Manager isn't accessible via Story instances") on instance access ("story.objects"), abstract models, or swapped models.

What QuerySet._clone copies vs. shares

Every public chaining method (filter, exclude, order_by, annotate, select_related, prefetch_related, defer, only, using, fetch_mode) starts by calling QuerySet._chain, which calls QuerySet._clone:

def _clone(self):
    c = self.__class__(
        model=self.model,
        query=self.query.chain(),
        using=self._db,
        hints=self._hints,
    )
    c._sticky_filter = self._sticky_filter
    c._for_write = self._for_write
    c._prefetch_related_lookups = self._prefetch_related_lookups[:]
    c._known_related_objects = self._known_related_objects
    c._iterable_class = self._iterable_class
    c._fetch_mode = self._fetch_mode
    c._fields = self._fields
    return c

Look closely at what _clone() copies, what it resets, and what it shares:

In-place mutation with PreventQuerySetCloning

Cloning an entire Query tree on every chained call is cheap for three user calls, yet wasteful inside Django’s own internals (such as create_reverse_many_to_one_manager or ForwardManyToOneDescriptor.get_prefetch_querysets) where Django constructs a brand-new private queryset and immediately applies three filters to it before anyone else holds a reference.

For those hot internal paths, Django defines PreventQuerySetCloning — a __slots__ = ("queryset",) context manager entered via QuerySet._avoid_cloning (QuerySet._avoid_cloning; notice the comment noting @contextlib.contextmanager is intentionally skipped for speed!). Inside with qs._avoid_cloning():, _cloning_enabled flips to False, so QuerySet._chain returns self directly and mutates the single QuerySet in place, then re-enables cloning on exit.

Verify manager synthesis, zero-SQL chaining, clone isolation, and _avoid_cloning() live on our newsroom "Story" model:

Recorded on Django 6.1.3 ch07-querysets script
Managers, QuerySet._clone(), and PreventQuerySetCloning
  type(Story.objects)=ManagerFromStoryQuerySet _queryset_class=StoryQuerySet built_with_as_manager=True
  chained 3 methods -> queries=0 distinct_qs=3 distinct_query=3
  clone shares _hints=False shares _known_related_objects=True
  inside _avoid_cloning(): same_qs_object=True cloning_restored=True

Where cloning and managers leak

Chaining builds an inert description in Python. Next, we cross the line where SQL actually fires — and examine the single most common caching trap in Django views — in Evaluation and _result_cache.