Django 6.1.3

1.2 One request, unwrapped

Django’s design bets

Why is Django built the way it is — batteries included, synchronous at its core, explicit about queries, and hostile to global object caches?

Watch an engineer arriving from SQLAlchemy, Rails, or FastAPI hit their first week debugging Django internals and you hear the same five complaints. Why did fetching the same row twice hit the database twice? Why did a template loop fire six hundred queries? Why did importing a model in a helper script crash before any code ran? Why does an async view still jump onto a thread pool?

Every one of those behaviours is the direct consequence of five architectural bets Django made early and still defends in 6.1.3. Understanding the bets turns twenty years of framework quirks into a single coherent map.

No identity map

Ask SQLAlchemy’s Session for primary key 1 twice in the same unit of work and it returns the exact same Python object from an in-memory identity map: first is second is True, and editing an attribute on one reference is immediately visible through the other.

Ask Django’s ORM for the same row twice and watch what actually runs on our newsroom project:

Recorded on Django 6.1.3 ch01-one-request script
No identity map: two queries for the same Story return distinct Python objects
  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"."slug" = %s LIMIT 21  params=('bridge-bond-passes',)
  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"."slug" = %s LIMIT 21  params=('bridge-bond-passes',)
  first == second -> True
  first is second -> False
  after mutating first.headline: second.headline -> 'Bridge bond passes council'
  queries=2

Two identical SELECT statements went over the wire, constructing two independent Python instances. first == second returns True only because Model.__eq__ compares concrete model classes and primary keys. Mutating the headline on the first instance in memory leaves the second instance completely untouched.

That single refusal shapes everything in Part II of this book. Because Django never deduplicates rows behind your back, you saw in One request from wire to HTML what happens when a template touches "story.corrections.all" three times: Django faithfully runs three queries unless you explicitly opt into QuerySet.select_related, QuerySet.prefetch_related, or Django 6.1’s QuerySet.fetch_mode.

Laziness confined to explicit seams

Although Django refuses hidden global caches, it leans heavily on deferred work. Almost every lazy object in the framework belongs to one of three clean shapes.

Proxy objects built on LazyObject — settings and the request user attached by AuthenticationMiddleware — look like real objects at import or middleware time while holding nothing but a sentinel (empty). Reading settings.DEBUG loads the settings module once; touching the request user runs a session and user query only on endpoints that actually ask who is logged in.

Query objects (QuerySet and its internal Query tree) defer database I/O across arbitrarily many chained filters, exclusions, and orderings until a caller demands rows. And resource objects — TemplateResponse and FieldFile — postpone rendering templates or opening storage files until the latest possible moment.

The trade-off is identical across every seam: laziness avoids wasted work on code paths that never touch the result, and pushes real I/O onto a later call site — like django.template.base.Template.render — where naive profiling or transaction boundaries can miss it.

Paying structural cost once at import time

When Python executes a Model subclass definition, Django does not wait for the first query to inspect your fields. ModelBase.__new__ runs immediately at import time: it strips every field object off the class dictionary, constructs an Options metadata container (_meta), installs Python descriptors for every column and foreign key, generates model-specific "DoesNotExist" (subclassing ObjectDoesNotExist) and MultipleObjectsReturned exceptions, and registers the finished class inside the global Apps registry. Forms repeat the exact same pattern with DeclarativeFieldsMetaclass.

Front-loading that work keeps per-request execution predictable and fast. The hidden bill arrives at startup: because ModelBase.__new__ looks up the model’s AppConfig while the class statement executes, importing a model before Django finishes populating its app registry crashes immediately with AppRegistryNotReady. That tension — fast runtime metadata versus strict import order — is the entire subject of Booting Django.

Loose coupling behind shared conventions

Django ships an ORM, template engine, form pipeline, session store, auth stack, admin site, cache framework, and in Django 6.1 a native background-task layer. Yet the framework tries hard to prevent those subsystems from reaching directly into one another’s private data structures.

The template engine knows nothing about Django models or querysets; it walks any Python iterable and resolves dotted names through a uniform dictionary, attribute, and index lookup. Middleware wraps HttpRequest and HttpResponseBase without knowing whether a view is a function, a generic class, or an admin changelist. Decoupled apps react to model saves and request lifecycles through synchronous Signal dispatchers rather than hard-coded cross-app imports.

A synchronous core adapted for ASGI

For its first fourteen years Django was strictly synchronous. One worker thread handled one HTTP request from start to finish, held one thread-local database connection, tracked one thread-local active language and timezone, and returned a complete response.

When asynchronous Python matured, Django deliberately refused to split the ecosystem in two with a separate async-only framework.

Because large parts of Django (database drivers, template rendering, and several built-in middleware classes) remain synchronous, BaseHandler.adapt_method_mode bridges every boundary between async and sync layers using sync_to_async and async_to_sync. Knowing where those thread-pool crossings sit — and how to keep a single synchronous middleware from bouncing an async endpoint off the event loop — is essential for running modern Django under ASGI.

Those five bets explain why Django’s internals are shaped the way they are. Before opening django.setup in Chapter 2, let’s meet the single newsroom application we run and measure across the rest of the book.