Django 6.1.3

Part II · The ORM

Chapter 7: QuerySets and laziness

The promiseA queryset behaves like a list.

The machineryA 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, 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

Figure 7.1 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 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 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.