Five Seconds to Load, Forty Queries to Blame: How to Prompt an LLM to Read Django ORM and Fix select_related Before Your Users Notice

A product page takes five seconds to load. The template looks innocent, the view has three lines, and the database is not even that big — a few tens of thousands of rows. You open django-debug-toolbar and see the honest answer: 312 queries, most of them identical, all fired from inside a {% for %} loop. That is the classic N+1, and you already know the words select_related and prefetch_related are supposed to fix it. What you do not know is which relation to pull, which one to leave alone, and why the "optimized" version somebody merged last month made the page slower instead of faster.

This is where an LLM actually earns its keep — but only if you stop asking it to "optimize my Django ORM queries" and start feeding it the real picture: the toolbar output, the QuerySet.explain() plan, the raw SQL log. Below is the prompt kit I keep coming back to, each one tested against a real page like the one above, with the kind of input it needs and the kind of answer that is worth reading.

Why "optimize my queries" is the worst prompt you can write

Ask a model to optimize a Django page without data and you get a lecture: add indexes, use select_related, avoid len() on a queryset. All true, none of it about your page. The model has no idea that Product.objects.get() fires 40 extra queries through product.category.parent in the template, because you never showed it the template.

The rule that follows from this is simple and it holds for every prompt below: the model is only as good as the artifact you paste in. A toolbar report, an .explain() output, a connection.queries dump — those are artifacts. "My page is slow" is not.

There is a second trap, and it is sneakier. The model will happily rewrite your queryset into something that looks optimized and is wrong: it will select_related a many-to-many field (which Django rejects outright), or prefetch_related a foreign key that your template then filters with .filter() inside the loop, silently re-triggering the query you thought you killed. You will not catch this by reading the diff. You catch it by running the page again with the toolbar open. More on the topic: “Twelve Prompts That Read EXPLAIN ANALYZE Better Than You Do — and the Three Moments When You Should Not Trust Them”.

The one input that changes everything A prompt with a real query count and a real SQL log gets a real answer. A prompt with adjectives gets a lecture. Paste the artifact, not the feeling.

Prompt 1: Turn the toolbar report into a named list of N+1s

Start here. The toolbar already told you the number; you need the model to tell you which queries are duplicates and where they come from.

Prompt:

I am pasting a django-debug-toolbar SQL panel export from a single page load. The page is a product listing.

For each distinct SQL statement below:

1. Group identical statements (same SQL, different bind parameters) and count them.
2. For each group with more than one execution, name the most likely Django ORM call that produced it (e.g. `product.category.name` in the template, a `for` loop over `order.items.all()`).
3. Mark which groups are N+1 candidates and which are legitimately repeated.

Then give me a table: query group

| count | likely source | N+1 yes/no.

Do not rewrite any code yet. I want the diagnosis first.

[PASTE TOOLBAR SQL EXPORT]

What you get back is a table where the 312-query page collapses into maybe six groups, and the biggest one is SELECT... FROM store_category WHERE id =? executed 180 times. That is the loop over product.category in the template. Now you know where to aim.

The reason this prompt works is that it forces the model to reason over counts and repetition, which is exactly the shape of an N+1 problem, instead of over code, which is where it starts guessing.

Prompt 2: Rewrite the eager loading — and prove it with the query count

Only now do you let the model touch the queryset. The trick is to make it commit to a number before you run anything.

Prompt:

Here is my current view and template. The toolbar showed 312 queries for this page.

Current queryset:

    products = Product.objects.filter(is_active=True)

The template loop accesses: product.category.name, product.category.parent.name,

product.images.all(), and product.tags.all().

Rewrite the queryset using select_related for forward FK/OneToOne relations and

prefetch_related for reverse FK and M2M. Then answer:

- How many queries will the new queryset fire in total on this page?
- Show the math: 1 for products + N for related + M for prefetch.
- Flag any relation where prefetch_related will be re-triggered because the
  template calls .filter() or .count() on it inside the loop.

Do not add indexes or caching. Just fix the eager loading and show the expected count.

A good answer looks like this and does the arithmetic honestly:

products = (

    Product.objects

    .filter(is_active=True)

    .select_related('category', 'category__parent')

    .prefetch_related('images', 'tags')

)

# 1 query for products
# + 0 for category and category__parent (JOINed via select_related)
# + 1 for images (prefetch)
# + 1 for tags (prefetch)
# = 4 queries total, down from 312.
Where the 312 queries go before the fix
Total queries on page load312
After select_related on category132 · 42.3%
After prefetch on images and tags4 · 1.3%

And it should warn you about the product.tags.all() inside a loop that also calls .count() — that count re-queries even with prefetch in place, because prefetch loads the objects but the count goes to the database. That warning is the difference between a model that understands Django and one that pastes select_related everywhere.

Check the relation direction before you trust the rewrite `select_related` only works on forward ForeignKey and OneToOne. Point it at a reverse FK or a ManyToMany and Django raises `FieldError` at query time — the model will often get this wrong on `related_name` fields, so read the field type, not the name.

Prompt 3: Read QuerySet.explain() and tell me what the database actually did

You fixed the N+1, the query count drops to four, and the page is still slow. Now the problem is not the number of queries — it is one query doing a sequential scan over a table you thought was indexed.

Prompt:

Here is the output of `Product.objects.filter(is_active=True).select_related('category').explain(analyze=True)` on PostgreSQL. The page still takes 3.2s after fixing N+1.

Read the plan and tell me:

1. Which node takes the most actual time, by percentage of total.
2. Is there a Seq Scan on a large table? What filter is it doing?
3. Does the JOIN from select_related change the plan versus without it?
4. What single index (columns, order) would most likely remove the bottleneck?

Quote the exact plan lines you are reasoning from. Do not guess at rows you cannot see.

[PASTE EXPLAIN ANALYZE OUTPUT]

The value here is that the model is reading a plan, not inventing one. When it says "the Seq Scan on store_product at 2.1s is 65% of runtime, and the filter is is_active = true with 48,000 rows scanned to return 900," you can verify that against the plan yourself. A partial index on (is_active) or a composite on (is_active, created_at) is now a concrete, checkable proposal rather than a guess. More on the topic: “Your Index Guess Is a Coin Flip: Prompts That Make an LLM Read EXPLAIN ANALYZE and Name the Bottleneck First”.

If your plan-reading needs to go deeper than one prompt, this is the same skill applied to a different database layer: Stop Guessing at Indexes: Prompts That Make an LLM Read EXPLAIN ANALYZE Like a DBA.

Prompt 4: Hunt the extra COUNTs and duplicate rows in annotate

Here is a failure that the toolbar hides and the plan does not show, because it is not slow — it is wrong. You add annotate(Count('reviews')) and annotate(Count('images')) to a listing, and suddenly every product shows a review count multiplied by its image count. That is the classic double-JOIN fan-out, and it is one of the places an LLM is genuinely good, because the bug is logical, not performance-related.

Prompt:

This queryset returns inflated counts — a product with 3 reviews and 4 images shows 12 reviews.

    Product.objects.annotate(

        review_count=Count('reviews'),

        image_count=Count('images'),

    )

Explain why the counts are multiplied. Then rewrite it using

Count(..., distinct=True) or subqueries, and tell me which approach costs

fewer queries. Show the corrected queryset and the SQL it produces.

Also check: is there an extra COUNT query being fired per row in the template

that I have not noticed?

The model should explain the fan-out — two JOINs multiply the rows, so Count counts the cross product — and offer Count('reviews', distinct=True). It should also mention the trade-off: distinct=True on a large table adds a sort or hash, so for big listings a Subquery with OuterRef is often cheaper. That trade-off is the useful part; the corrected code alone you could have found in the docs.

Prompt 5: Turn a raw SQL log into a prioritized fix plan

When you have twenty slow pages and no time, the fastest move is to dump connection.queries across a few requests and let the model rank them.

Prompt:

Below is a raw SQL log from `connection.queries` across three page loads

(product list, product detail, checkout). Each entry has sql and time.

Do three things:

1. Group by page and sum the time per page.
2. Within each page, list the top 3 statements by total time (count x time).
3. For each top statement, say whether the fix is eager loading
   (select_related/prefetch_related), an index, or a query that should not

   exist at all (e.g. a COUNT the template does not display).

Output a prioritized list: page

| statement | total time | fix type | one-line action.

Rank by total time, not by count.

[PASTE connection.queries LOG]

Ranking by total time rather than by query count is the whole point. A page can fire 200 fast queries that add up to 40ms and one slow query that adds up to 4 seconds. Optimizing the 200 is satisfying and pointless; the model, given the times, will usually point you at the one that matters. More on the topic: “Six Seconds to First Paint: The LLM Prompts That Find the One Request Killing Your Core Web Vitals”.

Where the LLM saves hours and where it burns them It saves hours on diagnosis (grouping duplicate queries, reading plans, explaining fan-out) because that is pattern-matching over data you hand it. It burns hours when you ask it to design the fix blind — it will produce plausible code that ignores your schema, your relation directions, and your template's actual access pattern.

Where the model quietly gets it wrong

Three failure modes show up again and again, and all three are cheap to catch if you know to look.

It confuses relation direction. Reverse FK and M2M go to prefetch_related; forward FK and OneToOne go to select_related. The model will sometimes swap them because the field name looks the same from both sides. Always check the field definition, not the call site.

It forgets that prefetch is lazy about filters. prefetch_related('tags') loads all tags, but product.tags.filter(is_active=True) inside the loop re-queries anyway. If your template filters related sets, the prefetch buys you nothing and the model often will not mention it unless you ask.

It optimizes the query count, not the wall clock. Four queries can be slower than forty if those four each scan a million rows. The number that matters is the one in the browser, not the one in the toolbar — which is why Prompt 3 and Prompt 5 exist.

The prompt habit that makes the rest work

If you take one thing from this, make it the input rule: paste the artifact, ask for a diagnosis, then ask for a fix, then ask for the expected query count. Every prompt above follows that order, and the order is why the answers are usable. The model is a fast, tireless reader of logs and plans. It is a mediocre guesser of your schema. Keep it on the reading side of that line and Django ORM debugging stops being a five-second mystery and becomes a fifteen-minute loop: measure, diagnose, fix, measure again.

For the broader picture of what else tends to break in a Django app once the page loads fast enough that users actually stay, there is a companion piece worth reading: Django and FastAPI — Python Web: What Actually Breaks in Production and How to Debug It in Advance.

← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text.