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, 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/ and django/ to see how Django wires those two classes together.
How BaseManager.from_queryset builds Manager
Look at line 176 of django/ — the entire definition of Django’s default Manager class is two lines:
class Manager(BaseManager.from_queryset(QuerySet)):
pass
Now read BaseManager and BaseManager:
- It inspects every function defined on the queryset subclass via
inspect..getmembers(..., predicate=inspect .isfunction) - It skips any method already defined on
cls, any private method starting with"_"(unless explicitly markedqueryset_only = False, such as_insertand_update), and any public method markedqueryset_only = True(such asQuerySet.deleteandQuerySet— which is why.as_manager "Storyraises.objects .delete()" AttributeErrorto prevent accidentally wiping an entire table!). - For every remaining method, it generates a forwarding wrapper (
getattr(self) and calls.get_queryset(), name)(*args, **kwargs) type(...)to synthesize a new subclass named"ManagerFromStoryQuerySet". - When our newsroom’s
"Story"declares"objects = StoryQuerySet,.as_manager()" QuerySetsimply invokes.as_manager BaseManageron.from_queryset Managerand stamps_built_with_as_manager = TruesoBaseManagercan serialize it cleanly into migrations!.deconstruct
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 hits the prefetch cache while "story misses it: BaseManager.all returns the already-cached queryset straight from the related manager’s get_queryset() without cloning!
Finally, remember ManagerDescriptor: BaseManager attaches a descriptor that returns the manager from Options 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:
- Copied (isolated):
Query.chainclones the internalQueryAST (so chainingQuerySet.filteronto a derived queryset never mutates the parent queryset’s"WHERE"clause!), andselfslices a copy of the prefetch tuple.._prefetch_related_lookups[: ] - Reset (never inherited):
_result_cachestarts back atNoneand_prefetch_donestarts atFalse! That is why cloning an already-evaluated queryset always yields a fresh, unevaluated queryset. - Shared by reference:
_known_related_objectsis passed straight across, and_hintsis shared whenever non-empty (hints or {}inQuerySetallocates a new.__init__ {}only when_hintsis empty!).
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) 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 (QuerySet; notice the comment noting @contextlib is intentionally skipped for speed!). Inside with qs, _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:
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
- Calling
"qs.filter(...)"without capturing the return value is a silent no-op. Because every chaining method clones and leaves the originalQuerySetuntouched, writing"qson its own line (as if mutating a Python.filter(status='published')" list) discards the filtered clone and queries the unfiltered table. - Storing a
QuerySetas a module global or class attribute freezes time — or leaks stale_result_cache. Never assign"ACTIVE_STORIES = Storyat module level: the first request to evaluate it populates its.objects .published()" _result_cachein memory for the life of the worker process (and anydjangoargument gets evaluated once at import time!)..utils .timezone .now - Mutating
_hintson a cloned queryset that already carried router hints mutates its parent. Because_clone()passeshints=selfdirectly when._hints _hintsis truthy, modifying_hintsin place affects sibling clones pointing to that same dict.
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.