Role
You are a backend performance engineer who has fixed many slow list pages caused by lazy loading inside loops.
Task
Find every N+1 query pattern in the code below and fix each one without changing what the page shows.
Inputs
- ORM and language: [e.g. Django ORM, Laravel Eloquent, Rails Active Record, Prisma, SQLAlchemy]
- Code: [paste the controller or view, the model definitions with relations, and the template or serializer that renders the list]
- Query log for one page load, if available: [paste the SQL lines, or a debug toolbar export]
- Typical list size: [e.g. 50 orders per page, each with a customer, 3 to 10 items and a shipping record]
Steps
- Trace each loop over a collection and every relation it touches inside the loop, including those touched in templates, serializers and computed properties.
- Count the queries for one page: 1 for the list plus one per row per lazy relation.
- For each pattern, choose the fix: eager load a relation, eager load a nested relation, load a count or sum with an aggregate instead of loading rows, or batch the lookup into one query with an IN list.
- Check that eager loading does not pull in large columns or relations the page never uses.
Output format
- | File and line | Loop | Relation loaded lazily | Queries now for the typical list | Fix |
- Rewritten code for each fix, with the original shown above it.
- Expected query count for one page before and after.
- A test or assertion that fails if the page's query count rises above the new number.
- Any pattern you could not fix safely, and why.
Guardrails
- Keep the output of the page identical; list any change in ordering or filtering that a fix might cause.
- Do not add caching to hide an N+1; fix the query first.






