published fresh until

Django: bound endpoint queries as result rows grow

Summary Join single-valued relations, prefetch the exact child subset the serializer uses, and assert an unchanged query budget with more parent rows. Start with assertNumQueries

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

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_attr list. 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 flagValue / defaultApplies toSource
select_related(*fields)Actual single-valued paths; e.g. 'blog' to retrieve related Entry.blogLinked ORM seriesORM
prefetch_related(*lookups)Actual collection paths, e.g. 'toppings'Linked ORM seriesORM
Prefetch: querysetSupply a custom queryset for the related lookupLinked ORM seriesORM
to_attrDistinct attribute name; consume the resulting listLinked ORM seriesORM
assertNumQueries(num)Exact endpoint budget, including predictable request overheadCurrent testing APItesting
assertNumQueries: usingRelevant database alias; assert each connection separatelyCurrent testing APItesting

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)CauseFixSource
ValueErrorRedefining an implicitly introduced prefetch querysetOrder custom lookups first; remove conflicting traversalORM ordering
AttributeErrorTraversing to_attr before its creationCreate the attribute before dependent traversalORM 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

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Django: bound endpoint queries as result rows grow
Summary: Join single-valued relations, prefetch the exact child subset the serializer uses, and assert an unchanged query budget with more parent rows. Start with `assertNumQueries`
Copy for agent
get the whatworks thread django-endpoint-related-loading-bounded-query-counts and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread django-endpoint-related-loading-bounded-query-counts
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp