Django 6.1.3

Part II · The ORM

Chapter 9: Connections, transactions, and migrations

The promiseThe database is always ready and migrations just diff models.

The machineryConnection lifecycles, atomic savepoints, on_commit hooks, how migrations replay history into a ProjectState graph, and how BaseDatabaseSchemaEditor rewrites live tables.

Above django/db/models/, Django feels stateless and immediate: call "Story.objects.create(...)" and a row lands on disk; edit "models.py", run "makemigrations" and "migrate", and the database matches your class definitions.

Open the bottom half of django/db/ and both halves of that promise dissolve. First, Django does not hold a pre-opened pool of sockets waiting for your views: ConnectionHandler isolates one lazy BaseDatabaseWrapper per thread, opens the socket only on the first query, runs every statement in autocommit unless wrapped in Atomic, and tears down expired or broken connections on "request_started" and "request_finished". Second, migrations never diff your Python models against the live database tables: MigrationLoader replays every historical migration file into an in-memory ProjectState and renders synthetic "__fake__" model classes inside StateApps before BaseDatabaseSchemaEditor translates abstract operations into backend-specific DDL.

Connection lifecycles and the real cost of autocommit

Figure 9.1 Every latency bar is parsed directly from ch09-bench on a real file-backed SQLite database using Django’s default settings, and every lifecycle hook is verified in ch09-database. Wrapping 100 saves in one atomic block cuts wall-clock time from 559.239 ms to 23.796 ms (23.50x faster), and pairing atomic with QuerySet.bulk_create reaches 8.738 ms (64.00x faster).

What closes Part II

This chapter traces the entire persistence boundary from socket to schema across seven steps:

We begin with how ConnectionHandler isolates thread-local connections, when BaseDatabaseWrapper.ensure_connection actually opens a socket, and how "CONN_MAX_AGE" and "CONN_HEALTH_CHECKS" interact with request signals. Next we inspect the five-class anatomy that lets SQLite, PostgreSQL, MySQL, and Oracle diverge cleanly behind one API via BaseDatabaseFeatures and BaseDatabaseOperations. From there we trace autocommit, nested Atomic savepoints, the "needs_rollback" poisoned-block trap, and why side effects belong inside on_commit commit hooks. Finally, we open the migration engine from end to end: MigrationGraph and historical ProjectState models, MigrationAutodetector and MigrationOptimizer, and MigrationExecutor driving BaseDatabaseSchemaEditor — including why altering one column on SQLite rebuilds the entire table.

We start at the bottom of the connection stack — how Django creates, reuses, and closes database connections per thread — in Connection handlers, CONN_MAX_AGE, and teardown.