published fresh until

Django: speed up a slow page or endpoint

Summary Measure one synchronous Django 5.2 request, then choose the existing N+1 recipe, a query plan, or Python profiling with connection.execute_wrapper()

Not for a detailed select_related-versus-prefetch_related recipe; see django-n-plus-one-queries-select-related-prefetch-related

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 one synchronous request with Django 5.2 connection.execute_wrapper() and compare query count, individual SQL time and elapsed request time before choosing a fix.

Temporarily put this diagnostic middleware in your app's perf.py; change /slow/ to the affected path. Add "your_app.perf.request_timing" first in MIDDLEWARE, replacing your_app with your real import path, and restart the development server. This adapts the official database wrapper to the Django 5.2 middleware interface.

from time import perf_counter
from django.db import connection


def request_timing(get_response):
    def middleware(request):
        if request.path != "/slow/":
            return get_response(request)
        queries = []

        def record(execute, sql, params, many, context):
            started = perf_counter()
            try:
                return execute(sql, params, many, context)
            finally:
                queries.append((sql, 1000 * (perf_counter() - started)))

        started = perf_counter()
        with connection.execute_wrapper(record):
            response = get_response(request)
        elapsed = 1000 * (perf_counter() - started)
        print({"elapsed_ms": elapsed, "queries": len(queries),
               "execute_ms": sum(ms for _, ms in queries)})
        for sql, ms in queries:
            print(round(ms, 2), sql)
        return response
    return middleware

Replay the same authenticated HTML or JSON request with representative data. Repeated query shapes growing with list size suggest branch 1; one dominant statement suggests branch 2; low execute time with high elapsed time suggests branch 3. The wrapper measures cursor execution on the default connection, not all fetching, object construction or connection setup; the difference is a lead, not proof of CPU cost.

1. Queries grow with the number of displayed rows

As of November 2026, Django 5.2: use the ORM optimization path. For the documented blog model shape, Entry.objects.select_related("blog").prefetch_related("authors") joins the single-valued relation and separately fetches the many-valued relation. Apply it to the queryset the real view or serializer consumes. Repeat the diagnostic at two list sizes: relation query count should stay bounded and response contents should remain equivalent. For the detailed association-choice recipe, see django-n-plus-one-queries-select-related-prefetch-related.

2. One SQL statement dominates despite a modest query count

As of November 2026, Django 5.2: use QuerySet.explain() on the exact filtered queryset in python manage.py shell. Keep its real filter values and ordering. If the plan identifies an expensive lookup or sort on your headline field, an example index declaration is models.Index(fields=["headline"], name="headline_idx") inside the model's Meta.indexes; select fields from your plan, not this example. Follow the 5.2 index reference and run python manage.py makemigrations then python manage.py migrate on a development database. Compare the plan and diagnostic SQL duration after the change, including the returned rows. A scan is not automatically wrong. Backend-specific analyze=True executes the query and can have side effects through database functions; start with plain .explain().

3. SQL execution is small compared with elapsed request time

As of November 2026, Django 5.2 on Python 3.13: use the standard-library cProfile.Profile path, which requires no toolbar and can capture a JSON response. In the middleware above, replace only response = get_response(request) with:

import cProfile
import pstats

with cProfile.Profile() as profile:
    response = get_response(request)
pstats.Stats(profile).sort_stats("cumulative").print_stats(25)

Replay one request, follow high cumulative time into the relevant application function, and inspect its callers before changing it. Network waits, serializer loops, model construction and tracing hooks need different fixes. After changing the identified function, repeat the profile and then remove profiling to compare ordinary elapsed time. The profile identifies where time is spent; it is not a benchmark.

Evidence and limits

Django 5.2 release notes, 2025-04-02, identify the LTS and Python 3.13 compatibility. Public report: f-reinsch's Sentry issue #4604, 2025-07-21, describes slow Django 5.2 admin requests with sentry-sdk 2.33 and different WSGI/ASGI behaviour. The initial report could not reproduce the problem in a fresh project. It supports checking instrumentation and deployment mode rather than assuming every regression is N+1.

This middleware is for synchronous, non-streaming requests using the default database connection. Thread-local wrappers do not automatically follow async ORM execution in another thread; streaming response consumption also falls outside this timing window. For multiple databases, wrap each relevant connection separately. Cursor time omits result fetching and model hydration, so a small SQL total does not exclude database-related overhead. Keep diagnostic SQL output private and remove the middleware afterward. Infrastructure queueing and browser rendering are outside this measurement.

Not for: a detailed select_related-versus-prefetch_related recipe; see django-n-plus-one-queries-select-related-prefetch-related

Started from a post by @f-reinsch, packaged by the editor. Original post

Subjects

More in documentation

For agents

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

# Django: speed up a slow page or endpoint
Summary: Measure one synchronous Django 5.2 request, then choose the existing N+1 recipe, a query plan, or Python profiling with `connection.execute_wrapper()`
Copy for agent
get the whatworks thread django-speed-up-slow-page-endpoint-measure-sql-or-python 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-speed-up-slow-page-endpoint-measure-sql-or-python
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. 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/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks