Part II · The ORM
Chapter 6: Models, metaclasses, and state
The promiseA model is a Python class.
The machineryHow ModelBase turns declarative field attributes into model options, descriptors, and database columns — and how every instance tracks its state against its row.
Open any Django tutorial and you meet a reassuring sentence: a model is just a Python class that subclasses Model. You declare "headline = CharField(max_length=160)", attach a "ForeignKey", tuck an ordering list inside "class Meta", and get a database table with Python attributes.
That simplicity is a deliberate illusion engineered at class-creation time. The moment Python finishes evaluating the body of a Model subclass, ModelBase disassembles the class dictionary you wrote, throws away "Meta", strips every field instance off the class, and replaces your declarations with a coordinated set of descriptors, immutable metadata tables, synthesized exception classes, and reverse accessors wired onto other models across the project.
What ModelBase builds — and what every row costs
ch06-models and every latency bar is parsed from ch06-bench. Look at two immediate consequences of how Model is engineered: keyword instantiation (11.28 us) is almost twice as slow as Model.from_db (5.99 us), and connecting a single no-op post_init receiver adds +22% overhead to every single row Django hydrates from SQL.From class definition to live database rows
Everything in Part II rests on the machinery inside a single model class and a single model instance.
At import time, ModelBase builds Options, routes fields and managers through contribute_to_class, synthesizes per-model exceptions — including Django 6.1’s "NotUpdated" alongside "DoesNotExist" and MultipleObjectsReturned — and registers the finished class in the app registry. Inside Options, Django keeps immutable cached field lists and maps (concrete_fields, many_to_many, related_objects, fields_map) alongside each field’s schema and migration bridge (db_type, get_prep_value, deconstruct).
At runtime, ordinary attribute reads like "story.body", "story.desk_id", and "story.desk" run through descriptors (DeferredAttribute, ForeignKeyDeferredAttribute, ForwardManyToOneDescriptor) backed by per-instance ModelState — which tracks whether the row is new (adding), which database it came from (db), its cached relations (fields_cache), and Django 6.1’s FetchMode (FETCH_ONE, FETCH_PEERS, or FETCH_RAISE).
Finally, mutating or removing rows reveals the sharpest real-world traps in the ORM: Model.save choosing between "INSERT" and "UPDATE" (and why a preset primary key can trigger both), Collector collapsing leaf deletions into a single fast "DELETE" until one signal listener forces hundreds of rows into Python memory (10.84x slower in our benchmark), and the dramatically different tables and "INNER JOIN" queries hidden behind abstract bases, multi-table inheritance, and proxy models.
We start at import time, watching Python execute a model class body and hand it to What ModelBase builds at import time.