---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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:

```text recording=ch01-one-request
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 (`django/db/models/base.py:Model.__eq__`). Mutating the headline on the first instance in memory leaves the second instance completely untouched.

> **Why.** An identity map buys fewer queries in exchange for invisible global state. Every loaded object must live inside a session dictionary until explicitly cleared — causing silent memory leaks in batch jobs and masking concurrent updates from other workers behind stale cached attributes. Django refuses that bargain: ORM caching stays strictly local to one `QuerySet._result_cache` or one instance's relation cache (`django/db/models/query.py:QuerySet._fetch_all`). The moment a queryset or model goes out of scope, Python frees it immediately.

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](one-request.md) 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` (`django/db/models/query.py: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` (`django/utils/functional.py: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 (`django/db/models/query.py:QuerySet`). And resource objects — `TemplateResponse` and `FieldFile` — postpone rendering templates or opening storage files until the latest possible moment (`django/template/response.py:SimpleTemplateResponse`, `django/db/models/fields/files.py:FieldFile`).

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 (`django/db/models/base.py:ModelBase.__new__`, `django/apps/registry.py:Apps.register_model`). Forms repeat the exact same pattern with `DeclarativeFieldsMetaclass` (`django/forms/forms.py: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](../startup.md).

## 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 (`django/tasks/base.py:Task`). 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 (`django/dispatch/dispatcher.py:Signal`) rather than hard-coded cross-app imports.

> **History.** Django was extracted in 2005 from the publishing system built by Adrian Holovaty and Simon Willison (joined closely by Jacob Kaplan-Moss) at the *Lawrence Journal-World* in Kansas. Newsroom deadlines dictated the architecture: editors needed a production admin site the same afternoon a reporter requested a new model, designers edited HTML templates without writing Python, and breaking-news traffic spikes rewarded fast, cacheable read pages over heavy object-relational session graphs. Twenty years later, autoescaping, `TemplateResponse`, `ModelAdmin`, and explicit query optimization still carry that newsroom DNA.

## 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.

> **History.** In May 2019, Andrew Godwin laid out Django's async roadmap in DEP 0009 (`deps:accepted/0009-async.rst`): *"The plan is not to remove synchronous Django - the plan is to keep that around, working as it does now, with asynchronous code being an option for those that feel they need the extra performance or flexibility."* Every piece of modern async Django — `ASGIHandler`, coroutine views, async middleware, `asgiref.local.Local`, and async ORM wrappers (`acount`, `afirst`, `aiterator`) — was designed inside that single compatibility constraint.

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` (`django/core/handlers/base.py:BaseHandler.adapt_method_mode`, `asgiref:asgiref/local.py:Local`). 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.
