---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/db/models/manager.py: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**:

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

Now read `BaseManager.from_queryset` (`django/db/models/manager.py:BaseManager.from_queryset`) and `BaseManager._get_queryset_methods` (`django/db/models/manager.py: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` (`django/db/models/query.py: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` (`django/db/models/manager.py:BaseManager.all`):

```python
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` (`django/db/models/manager.py:ManagerDescriptor`): `BaseManager.contribute_to_class` attaches a descriptor that returns the manager from `Options.managers_map` (`django/db/models/options.py: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` (`django/db/models/query.py:QuerySet._chain`), which calls **`QuerySet._clone`** (`django/db/models/query.py:QuerySet._clone`):

```python
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.chain` (`django/db/models/sql/query.py:Query.chain`) clones the internal `Query` AST (so chaining `QuerySet.filter` onto a derived queryset never mutates the parent queryset's `"WHERE"` clause!), and `self._prefetch_related_lookups[:]` slices a copy of the prefetch tuple.
- **Reset (never inherited):** **`_result_cache` starts back at `None`** and `_prefetch_done` starts at `False`! That is why cloning an already-evaluated queryset always yields a fresh, unevaluated queryset.
- **Shared by reference:** `_known_related_objects` is passed straight across, and `_hints` is shared whenever non-empty (`hints or {}` in `QuerySet.__init__` allocates a new `{}` only when `_hints` is empty!).

## In-place mutation with `PreventQuerySetCloning`

Cloning an entire `Query` (`django/db/models/sql/query.py: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` (`django/db/models/query.py:PreventQuerySetCloning`) — a `__slots__ = ("queryset",)` context manager entered via `QuerySet._avoid_cloning` (`django/db/models/query.py: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:

```text recording=ch07-querysets
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 original `QuerySet` untouched, writing `"qs.filter(status='published')"` on its own line (as if mutating a Python `list`) discards the filtered clone and queries the unfiltered table.
- **Storing a `QuerySet` as a module global or class attribute freezes time — or leaks stale `_result_cache`.** Never assign `"ACTIVE_STORIES = Story.objects.published()"` at module level: the first request to evaluate it populates its `_result_cache` in memory for the life of the worker process (and any `django.utils.timezone.now` argument gets evaluated once at import time!).
- **Mutating `_hints` on a cloned queryset that already carried router hints mutates its parent.** Because `_clone()` passes `hints=self._hints` directly when `_hints` is truthy, modifying `_hints` in 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](caching.md).
