---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The ORM
promise: A model is a Python class.
contents: metaclass, options-and-fields, descriptors, instance-state, saving, deleting, inheritance
---

# Models, metaclasses, and state

How `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` (`django/db/models/base.py:Model`) subclass, `ModelBase.__new__` (`django/db/models/base.py:ModelBase.__new__`) 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

```text figure=metaclass-blueprint
ModelBase.__new__ transformation on Story (Django 6.1.3) and instantiation latency

1. Class body -> ModelBase.__new__ -> live Story.__dict__ & _meta:
   headline = CharField(...)        -> DeferredAttribute
   desk = ForeignKey(Desk, ...)     -> ForeignKeyDeferredAttribute (desk_id) + ForwardManyToOneDescriptor (desk) + Desk.stories
   beats = ManyToManyField(...)     -> ManyToManyDescriptor
   status = CharField(choices=...)  -> DeferredAttribute + get_status_display (functools.partialmethod)
   objects = StoryQuerySet.as_mgr() -> ManagerDescriptor
   class Meta                       -> popped into _meta (Options) + DoesNotExist, MultipleObjectsReturned, NotUpdated

2. Model instantiation cost on Story (50,000 calls x 5 trials, microseconds):
   Story(*values) [positional fast path]         5.63 us  (0.94x)
   Story.from_db(...) [ModelIterable path]       5.99 us  (1.00x)
   Story.from_db(...) + 1 post_init receiver     7.31 us  (1.22x)
   Story(**kwargs) [keyword instantiation]      11.28 us  (1.88x)
   Story(**kwargs) + 1 post_init receiver       12.78 us  (2.13x)
```

*Every descriptor mapping is verified from `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.__new__` builds `Options` (`django/db/models/options.py: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` (`django/db/models/base.py: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` (`django/db/models/deletion.py: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.__new__` builds at import time](models/metaclass.md).
