One request from wire to HTML
What actually wakes up inside Django between a web server handing over a request dictionary and receiving back HTML bytes?
Take the Wednesday edition front of our newsroom project at "/. Suppose someone writes the shortest idiomatic generic ListView that satisfies the specification: fetch the edition matching the URL slug, return its published stories, and render the edition template.
class NaiveEditionListView(ListView):
model = Story
template_name = "newsroom/edition.html"
context_object_name = "stories"
def get_queryset(self):
self.edition = get_object_or_404(Edition, slug=self.kwargs["issue_date"])
return Story.objects.filter(edition=self.edition, status=Story.Status.PUBLISHED)
The template ("newsroom/) loops over the stories context variable and prints each story’s headline, desk name, reporter name, and — if the story has any corrections — how many:
{% for story in stories %}
<li>
<a href="{% url 'story-detail' slug=story.slug %}">{{ story.headline }}</a>
<span class="byline">{{ story.desk.name }} · {{ story.reporter.name }}</span>
{% if story.corrections.all %}
<span class="corrections">({{ story.corrections.all|length }} correction{{ story.corrections.all|length|pluralize }})</span>
{% endif %}
</li>
{% endfor %}
The Wednesday edition holds four published stories, two of which have corrections. Before looking at the recording below, make an honest guess: how many SQL queries does this view run, and when in the call stack do they fire?
Most experienced Django engineers count carefully and answer fourteen: one query for the edition, one for the four stories, four for each story’s desk, four for each reporter, and four for each story’s corrections (1 + 1 + 4 + 4 + 4 = 14).
The machine’s answer
Run that exact view against Django 6.1.3 and the answer is not fourteen. It is eighteen.
Naive view on 4 stories (2026-11-25): 17 of 18 queries fire inside Template.render
NaiveEditionListView.dispatch(issue_date='2026-11-25')
NaiveEditionListView.get_queryset
SQL SELECT "newsroom_edition"."id", "newsroom_edition"."issue_date", "newsroom_edition"."slug", "newsroom_edition"."title", "newsroom_edition"."status", "newsroom_edition"."published_at" FROM "newsroom_edition" WHERE "newsroom_edition"."slug" = %s LIMIT 21 params=('2026-11-25',)
NaiveEditionListView.render_to_response -> TemplateResponse (unrendered)
TemplateResponse.render(template=['newsroom/edition.html', 'newsroom/story_list.html'])
Template.render('newsroom/edition.html')
SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id" FROM "newsroom_story" WHERE ("newsroom_story"."edition_id" = %s AND "newsroom_story"."status" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC params=(2, Story.Status.PUBLISHED)
SQL SELECT "newsroom_desk"."id", "newsroom_desk"."name", "newsroom_desk"."slug", "newsroom_desk"."section_code" FROM "newsroom_desk" WHERE "newsroom_desk"."id" = %s LIMIT 21 params=(1,)
SQL SELECT "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."email", "newsroom_reporter"."desk_id", "newsroom_reporter"."user_id" FROM "newsroom_reporter" WHERE "newsroom_reporter"."id" = %s LIMIT 21 params=(1,)
SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" = %s ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC params=(1,)
SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" = %s ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC params=(1,)
SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" = %s ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC params=(1,)
...
TRAP naive 4-story run: queries=18 html_bytes=1219 identical_html=True
Look at those three identical lines in the middle of the trace, all with params=(1,). Why did story #1 query the corrections table three times in a row?
Because the template wrote "story three times. Without prefetching, every evaluation of "story calls QuerySet.all via the related manager and constructs a fresh, uncached QuerySet. The {% if story branch runs the first SELECT to check truthiness; finding two rows, the template enters the if block and runs a second SELECT to compute |length, and then a third SELECT to feed |length|pluralize! On the two stories that have corrections, each story fires three identical queries instead of one — adding four unexpected queries on top of the fourteen you predicted.
On four stories in local development, eighteen queries take 6, so nobody notices. Now put a two-hundred-story Sunday edition behind that exact same view and compare it against the real view in our newsroom project, which chains QuerySet (for desk and reporter) and QuerySet (for corrections) onto get_queryset.
Naive vs. eager view: 4 stories vs. 200 stories (query counts and byte parity)
view stories in_view in_template total_sql html_bytes
naive 4 1 17 18 1219
eager 4 1 2 3 1219
TRAP naive 200 1 641 642 36394
eager 200 1 2 3 36394
identical_html_4=True identical_html_200=True
Measured request time: naive vs. eager view (median of 7 warm runs, in-memory SQLite)
view stories sql view_ms render_ms total_ms least_ms
naive 4 18 0.41 6.12 6.52 6.45
eager 4 3 0.44 1.66 2.10 2.07
TRAP naive 200 642 0.43 208.54 208.98 204.69
eager 200 3 0.52 19.12 19.65 19.50
at 200 stories (zero network latency): naive is 10.6x slower than eager; 99.8% of naive time spent inside TemplateResponse.render
Both views return 36,394 identical bytes of HTML. Yet even against an in-memory SQLite database where network latency is literally zero, the naive view runs 642 SQL queries and spends 208.98 ms — 10.6x slower than the eager view’s 19.65 ms. Over a real PostgreSQL connection at half a millisecond per round-trip, those 639 extra queries add a third of a second of pure network wait before the database parses a single row.
And look again at the view-time column ("view_ms"): 0.43 ms out of 208.98 ms. To understand how 99.8% of a view’s work happens after the view function has already returned, we need to trace the whole request from the WSGI server dictionary to the moment the response closes.
The whole WSGI lifecycle on one page
Here is the real newsroom view (GET /) executed end to end through WSGIHandler, with every framework boundary and SQL statement recorded in the exact order Django runs it.
WSGIHandler: GET /editions/2026-11-25/ through desk/
WSGIHandler.__call__(PATH_INFO='/editions/2026-11-25/')
signal request_started (sender=WSGIHandler)
WSGIRequest.__init__(GET /editions/2026-11-25/)
BaseHandler.get_response
TimingHeaderMiddleware.__call__
BaseHandler._get_response
URLResolver.resolve('/editions/2026-11-25/')
URLResolver.resolve('editions/2026-11-25/')
EditionListView.dispatch(issue_date='2026-11-25')
EditionListView.get_queryset
SQL SELECT "newsroom_edition"."id", "newsroom_edition"."issue_date", "newsroom_edition"."slug", "newsroom_edition"."title", "newsroom_edition"."status", "newsroom_edition"."published_at" FROM "newsroom_edition" WHERE "newsroom_edition"."slug" = %s LIMIT 21 params=('2026-11-25',)
EditionListView.render_to_response -> TemplateResponse (unrendered)
TemplateResponse.render(template=['newsroom/edition.html', 'newsroom/story_list.html'])
Template.render('newsroom/edition.html')
SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id", "newsroom_desk"."id", "newsroom_desk"."name", "newsroom_desk"."slug", "newsroom_desk"."section_code", "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."email", "newsroom_reporter"."desk_id", "newsroom_reporter"."user_id" FROM "newsroom_story" INNER JOIN "newsroom_desk" ON ("newsroom_story"."desk_id" = "newsroom_desk"."id") INNER JOIN "newsroom_reporter" ON ("newsroom_story"."reporter_id" = "newsroom_reporter"."id") WHERE ("newsroom_story"."edition_id" = %s AND "newsroom_story"."status" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC params=(2, Story.Status.PUBLISHED)
SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" IN (%s, %s, %s, %s) ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC params=(1, 3, 2, 4)
start_response('200 OK', headers=[Content-Type, X-Frame-Options, Content-Length, X-Desk-Ms, X-Content-Type-Options, Referrer-Policy, Cross-Origin-Opener-Policy])
HttpResponseBase.close
signal request_finished (sender=WSGIHandler)
done: status='200 OK' queries=3 html_bytes=1219 has_x_desk_ms=True
ch01-bench. The dashed vertical wall separates what runs inside the view from what runs after the view returns.Follow the trace from top to bottom and watch how six subsystems hand the baton across that single call stack.
From WSGI dictionary to middleware onion
A WSGI server — Gunicorn, uWSGI, or Django’s own development server — knows nothing about Django. It calls WSGIHandler with two arguments: a plain Python dictionary (environ) holding the HTTP method, path, headers, and input stream, and a start_response callback.
Before Django even constructs a request object, it records the thread-local script prefix from "SCRIPT_NAME" and broadcasts request_started. Database connection wrappers listen to request_started so they can discard old or broken sockets before any view runs SQL. Only then does WSGIRequest wrap environ. Even that constructor stays lazy: it extracts the method and path, wraps "wsgi.input" in a LimitedStream capped at "CONTENT_LENGTH", and leaves query strings, cookies, and POST bodies completely unparsed behind properties until code reads them.
Next, BaseHandler activates the thread-local URLconf and calls BaseHandler. Although the settings file lists eight middleware strings in a flat list, BaseHandler folded them inside-out into a single nested chain of closures when WSGIHandler was created. Only our custom timing wrapper is printed in the trace, yet all seven built-in middleware layers wrap the same call — which is why four security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Cross-Origin-Opener-Policy) show up on line 20 without the view setting a single header.
Resolution, one eager query, and an unrendered response
At the innermost point of the onion sits BaseHandler. It calls URLResolver, which strips the leading slash and matches the compiled route pattern, capturing issue_date="2026-11-25". Notice why URLResolver appears twice in the trace: once on the root resolver ("/) and once on the pattern match beneath it.
BaseHandler invokes the callable returned earlier by View.as_view. That closure allocates a brand-new view instance for this request alone — so per-request attributes stored on the view never bleed between concurrent requests — calls View.setup, and enters View.dispatch, which routes "GET" to BaseListView.get.
Inside get_queryset, calling get_object_or_404 forces immediate database evaluation because the view needs the edition row right now. That fires SQL #1. Notice the LIMIT 21 at the end of the SQL: QuerySet.get asks for up to 21 rows rather than 2 so that if a query matches duplicates, the MultipleObjectsReturned error message can report whether there were 2, 5, or “more than 20” matching rows without loading an entire table.
The queryset returned by get_queryset, however, has not touched SQLite. BaseListView.get puts that unevaluated QuerySet into the context dictionary and calls render_to_response, which constructs a TemplateResponse and returns it unrendered. Touching SimpleTemplateResponse or iterating the response before rendering raises ContentNotRenderedError.
Deferred rendering wakes up the ORM
Control returns to BaseHandler, which checks whether the response exposes a callable render method. First it runs any process_template_response middleware hooks — the entire reason TemplateResponse defers rendering is so middleware can still swap the template name or enrich the context before HTML is frozen. Then Django calls SimpleTemplateResponse.
SimpleTemplateResponse resolves "newsroom/ and calls Template.render. When the template reaches {% for story in stories %}, Python calls iter on the QuerySet, triggering QuerySet. Only at that instant does SQLCompiler compile and send SQL #2 — a single INNER JOIN pulling each story alongside its desk and reporter — followed immediately by SQL #3, which collects the four returned primary keys (1, 3, 2, 4) and fetches all matching corrections in one IN (...) query, stashing them on each story’s prefetch cache. Now when the template checks "story three times per story, all three reads come straight from Python memory with zero extra SQL.
Unwind, hand-off, and request_finished
With 1,219 HTML bytes now sitting in SimpleTemplateResponse, the response unwinds outward through every middleware layer. The timing wrapper computes elapsed milliseconds and attaches "X-Desk-Ms"; XFrameOptionsMiddleware and SecurityMiddleware stamp the four browser security headers; WSGIHandler calls start_response("200 OK", response_headers) and hands the response object back to the WSGI server as an iterable of byte chunks.
Only after the WSGI server finishes streaming those bytes to the client does it call HttpResponseBase. close invokes every registered resource closer (such as closing open request upload files) and emits request_finished, giving database backends their cue to close expired connections.
That single thirty-line trace raises an immediate architectural question: why did Django choose lazy querysets, unrendered template responses, no cross-query object cache, and a nested synchronous middleware stack in the first place? Those decisions were not accidents — they are five deliberate design bets that explain the rest of the framework.