What this prompt does
This prompt frames the model as a senior Django engineer and asks for working before/after code, not generic ORM advice. You paste the slow [view] and your [toolbar_findings] from django-debug-toolbar, set the [traffic] level and [django_version], and it identifies each N+1 pattern, applies select_related/prefetch_related, trims columns with only()/values(), and replaces Python-side aggregation with database annotations.
The structure works because it targets real offenders instead of guessing. Feeding [toolbar_findings] grounds the fixes in the actual query list firing on the page, so the model collapses the relations that genuinely fire in a loop. [traffic] is used to rank the fixes by impact, so the busiest page's hotspots come first. [django_version] keeps the ORM syntax current. The deliverable to state expected query-count reduction per request makes the payoff measurable rather than hand-waved, and pasting the real view keeps the refactor aligned with code you actually run.
When to use it
- A list view balloons to hundreds of queries because a template touches a relation per row.
- You have django-debug-toolbar output and want fixes aimed at the real offenders.
- You need before/after code for each hotspot, not generic advice to "use select_related".
- You're doing Python-side aggregation loops that should be database annotations.
- You're hauling unused columns and want
only()/values()applied where it helps. - You want fixes ranked by page traffic so you tackle the heaviest pages first.
- You want to drop to
values()where a view needs columns, not full model instances.
Example output
You get the refactored view code with select_related, prefetch_related, only(), and annotations applied, before/after snippets for each hotspot, and a short table of query counts before and after per request. The table makes the win concrete -- e.g. a view dropping from hundreds of queries to a handful -- and the fixes are ranked so the highest-traffic page comes first, letting you spend effort where it returns the most.
Pro tips
- Paste the actual
[view]and the real[toolbar_findings]; the quality of the fixes depends on the model seeing the true query list. - Set
[traffic]honestly so the ranking puts your busiest page's hotspots at the top. - Give the right
[django_version]so the suggested ORM APIs match what you can run. - Reach for annotations over Python loops -- pushing aggregation into the database is usually the single biggest win on a heavy page.
- Verify the before/after query counts yourself in debug-toolbar; the model's estimate is a guide, not a measurement.
- Watch that
only()doesn't strip a column the template later accesses, or you'll re-trigger queries you just removed. - Prefer
values()overonly()when the view just needs a few fields and no model instances downstream.