What this thread does
Do first: wrap the fully rendered endpoint request in assertNumQueries(expected) and compare small and larger result sets.
Short answer
As of November 2026, this card targets Django 5.2. Load the relations actually serialized and hold the query budget constant as parent count grows.
Choose / don't choose
select_related: choose foreign keys/one-to-one relations; don't use it for collections.- Collection prefetch: choose many-to-many collections; don't filter each manager afterward (ORM).
- Filtered child lists: choose a named
to_attrlist. Anssi Kääriäinen's custom-prefetch ticket motivates explicit subsets; follow the current API rather than historical proposals.
Not for: single-statement SQL or Python CPU diagnosis; see django-speed-up-slow-page-endpoint-measure-sql-or-python.
Settings that matter
| Setting or flag | Value / default | Applies to | Source |
|---|---|---|---|
select_related(*fields) | Actual single-valued paths; e.g. 'blog' to retrieve related Entry.blog | Linked ORM series | ORM |
prefetch_related(*lookups) | Actual collection paths, e.g. 'toppings' | Linked ORM series | ORM |
Prefetch: queryset | Supply a custom queryset for the related lookup | Linked ORM series | ORM |
to_attr | Distinct attribute name; consume the resulting list | Linked ORM series | ORM |
assertNumQueries(num) | Exact endpoint budget, including predictable request overhead | Current testing API | testing |
assertNumQueries: using | Relevant database alias; assert each connection separately | Current testing API | testing |
Illustration: Prefetch('pizzas', queryset=Pizza.objects.filter(vegetarian=True), to_attr='vegetarian_menu'); serialize restaurant.vegetarian_menu. (ORM).
Order of operations
1. Inventory relation reads in serializers, templates, properties and string representations. Profile before changing queries; queryset evaluation and caches matter (optimization). 2. Apply loading to the queryset the endpoint actually consumes. Calling related.filter(...) after prefetch issues a fresh query: put the filter in Prefetch(queryset=...) and read its to_attr list (ORM). 3. Build fixtures and authenticate outside the measurement. Assert request plus lazy response rendering inside with self.assertNumQueries(expected):. Repeat with smaller and larger populated parent sets, using the same expected count. Assert response content too, so omitted children cannot falsely improve the count (testing API). 4. A per-parent regression must fail the larger fixture; inspect its query list rather than raising the budget. Re-evaluate page size and child volume when prefetch memory increases (optimization).
Known failures and fixes
| Error (short quote) | Cause | Fix | Source |
|---|---|---|---|
ValueError | Redefining an implicitly introduced prefetch queryset | Order custom lookups first; remove conflicting traversal | ORM ordering |
AttributeError | Traversing to_attr before its creation | Create the attribute before dependent traversal | ORM ordering |
Missing
- The linked source does not confirm: the suggested one-parent/twenty-parent fixture sizes.
- Actual model fields and measured endpoint budget are unspecified. Example names must be adapted to the schema.
- A constant query count alone does not bound query time, transferred rows or serialization cost.
Started from a post by @Django documentation team, packaged by the editor. Original post