---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The ORM
promise: A queryset behaves like a list.
contents: cloning, caching, iterables, select-related, prefetch-related, fetch-modes, bulk-writes
---

# QuerySets and laziness

A `QuerySet` is an unexecuted query description until something demands rows; chaining copies the description without touching the database, and the first evaluation fills an in-memory result cache.

You can iterate a `QuerySet` (`django/db/models/query.py:QuerySet`), call `len()` on it, test `if qs:`, or slice `"qs[:2]"`, so every newcomer treats it like a smart Python `list` backed by SQL.

That resemblance holds right up until production traffic arrives — and then every divergence between a `QuerySet` and a `list` turns into an incident. Chaining filters allocates cloned query trees without sending a byte to the database; checking `if qs:` before slicing `"qs[:2]"` silently downloads the entire table instead of emitting `"LIMIT 2"`; fetching full model instances costs eleven times more time and twelve times more RAM than a flat values list; and traversing relations inside a loop without the right fetch strategy multiplies one query into seventy-three.

## Two stages in Python, five hydration costs in SQL

```text figure=lazy-pipeline
QuerySet two-stage lifecycle & iterable cost on Django 6.1.3 (Python 3.14.8)

1. Stage 1 (chaining in Python, 0 SQL) -> _fetch_all() -> Stage 2 (evaluation into _result_cache):
   Stage 1: filter(), exclude(), order_by(), qs[:2] clone sql.Query via _chain() -> _clone() (_result_cache = None)
   Stage 2: iter(), len(), bool(), list(), repr(), qs[0] run SQL once and populate _result_cache
   Trap:    bool(qs) [if qs:] fetches ALL rows without LIMIT before a later qs[:2] slices in Python

2. Hydrating 500 Story rows by iterable class (7 trials + tracemalloc peak KB):
   ModelIterable [all()]                          5.597 ms · 492.6 KB  (1.00x)
   ModelIterable [only('id','headline','slug')]   3.244 ms · 207.2 KB  (0.58x)
   ValuesIterable [values('id','headline','slug')]0.759 ms · 150.7 KB  (0.14x)
   ValuesListIterable [values_list(...)]          0.655 ms ·  72.9 KB  (0.12x)
   FlatValuesListIterable [flat=True]             0.510 ms ·  40.9 KB  (0.09x)
```

*Every timing and peak-memory measurement is parsed from `ch07-bench` and every lifecycle transition is verified in `ch07-querysets`. Notice how identical SQL rows cost `5.597 ms` and `492.6 KB` when hydrated into `500` full model instances versus `0.510 ms` and `40.9 KB` through `FlatValuesListIterable` (`11.0x` faster and `12.0x` leaner).*

## What actually lives inside a `QuerySet`

Open `django/db/models/query.py` and you find two completely separate halves stitched into one class.

The first half is a pure-Python builder. A `Manager` (`django/db/models/manager.py:Manager`) dynamically forwards public `QuerySet` methods through `BaseManager.from_queryset`, while every chaining method calls `QuerySet._chain` and `QuerySet._clone` to duplicate the underlying `Query` tree (`django/db/models/sql/query.py:Query`) without touching the database — unless Django temporarily opts into in-place mutation via `PreventQuerySetCloning`. Nothing hits the wire until an evaluating operation invokes `QuerySet._fetch_all`, populating `"_result_cache"` once and turning subsequent `count()`, `exists()`, and slicing calls into zero-SQL memory reads.

The second half controls **what rows come back and how many round-trips they cost**. Swapping `"_iterable_class"` lets `ModelIterable`, `ValuesIterable`, `ValuesListIterable`, and `FlatValuesListIterable` reshape the exact same cursor stream, while `QuerySet.iterator` streams chunks without filling `"_result_cache"`. For relationships, `QuerySet.select_related` folds single-valued foreign keys into one SQL `"JOIN"` unpacked by `RelatedPopulator`; `QuerySet.prefetch_related` batches reverse and many-to-many lookups into `"IN (...)"` queries stitched into `"_prefetched_objects_cache"`; and **Django `6.1`'s `FetchMode` protocol** (`FETCH_ONE`, `FETCH_PEERS`, `FETCH_RAISE`) tracks sibling instances with `weakref.ref` peers to collapse forward-FK N+1s automatically — or raise `FieldFetchBlocked` the instant code attempts a lazy query! Finally, `QuerySet.update`, `QuerySet.bulk_create`, and `QuerySet.bulk_update` bypass per-row `Model.save` loops altogether.

We begin at the very first dot after a model class — how `"Story.objects.published()"` forwards through a manager and clones without touching SQL — in [Chaining, cloning, and managers](querysets/cloning.md).
