queries_in_loops
Detect database queries executed inside loops in Django code, identifying N+1 patterns and suggesting fixes like prefetching or moving constants.
Instructions
Database work written inside a loop, split by what the fix is.
The template and serializer checks here find the N+1 a framework causes.
This finds the one somebody wrote by hand, which is where it lives in a
codebase whose views build their responses themselves.
Three shapes share one appearance and need three different fixes:
Customer.objects.get(pk=order.customer_id) uses the loop variable:
once per row, needs a bulk
fetch or a prefetch
Config.objects.get(key="vat") does not: the same
question N times for the
same answer, move it above
the loop
order.save() N round trips; bulk_update
fixes it and skips signals
django-check does static N+1 for relation access in a loop and is the
closest existing tool; nplusone and the debug toolbar find it at runtime.
The separation is what is added here.
Args:
search_path: directory to scan. Defaults to the configured project.
include_writes: also report save()/delete() inside a loop.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| search_path | No | ||
| include_writes | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||