Django 6.1.3

6.4 Models, metaclasses, and state

ModelState, instantiation, and from_db

How does a model instance know whether it came from the database or was constructed in memory, and why does Model.from_db skip default field computations?

Every model instance carries two dictionaries of truth: its ordinary "instance.__dict__" (holding column values like "id", "headline", "desk_id") and a tiny companion object at "instance._state", an instance of ModelState.

Inside django.db.models.base.ModelState: lazy descriptors to save per-row memory

Open django/db/models/base.py lines 462–499:

class ModelStateFieldsCacheDescriptor:
    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.fields_cache = {}
        return res

class ModelStateFetchModeDescriptor:
    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.fetch_mode = FETCH_ONE
        return res

class ModelState:
    db = None
    adding = True
    fields_cache = ModelStateFieldsCacheDescriptor()
    fetch_mode = ModelStateFetchModeDescriptor()
    peers = ()

Look at how carefully ModelState avoids per-row allocations when a queryset materializes ten thousand rows!

Model.__init__ vs. Model.from_db and the DEFERRED sentinel

Now open Model.__init__ and Model.from_db.

Read lines 524–545 of Model.__init__ carefully. Django maintains two completely separate initialization loops inside __init__:

  1. The positional fast path (if not kwargs:, lines 524–533): Zips positional args straight across Options.concrete_fields and calls setattr(self, field.attname, val) — skipping every entry equal to DEFERRED, a module-level sentinel object! Because every concrete field receives either its SQL value or DEFERRED, the trailing for field in fields_iter: loop never executes a single iteration and Field.get_default is never called.
  2. The keyword path (else:, lines 534–613): Walks Options.fields, checks for duplicate positional+keyword arguments, pops both Field.name (related instances) and Field.attname ("_id" integers) from kwargs, calls Field.get_default for every omitted concrete field, and validates leftover keys against _property_names and virtual fields before raising TypeError on unexpected keywords.

Now look at Model.from_db (lines 617–630), the classmethod ModelIterable calls for every row coming off a database cursor:

@classmethod
def from_db(cls, db, field_names, values, *, fetch_mode=None):
    if len(values) != len(cls._meta.concrete_fields):
        values_iter = iter(values)
        values = [
            next(values_iter) if f.attname in field_names else DEFERRED
            for f in cls._meta.concrete_fields
        ]
    new = cls(*values)
    new._state.adding = False
    new._state.db = db
    if fetch_mode is not None:
        new._state.fetch_mode = fetch_mode
    return new

That design delivers two massive wins simultaneously:

Measure both effects — and the hidden cost of a single post_init signal receiver — live on Django 6.1.3:

Recorded on Django 6.1.3 ch06-bench script
Model instantiation cost on Story (50,000 calls x 5 trials, microseconds)
  path                                         us_per_call   relative
  Story(*values) [positional fast path]               5.63      0.94x
  Story.from_db(...) [ModelIterable path]             5.99      1.00x
  Story(**kwargs) [keyword instantiation]            11.28      1.88x
  Story.from_db(...) + 1 post_init receiver           7.31      1.22x
  Story(**kwargs) + 1 post_init receiver             12.78      2.13x

At 5.99 us per row vs 11.28 us (1.88x), Model.from_db’s positional fast path cuts pure-Python instantiation time nearly in half! And notice line 8: connecting even one empty post_init receiver adds +1.32 us (+22%) to every single model row hydrated from the database — because Model.__init__ fires both pre_init (line 511) and post_init (line 615) on every instance!

Identity, equality, and why unsaved models are unhashable

Look at Model.__eq__ and Model.__hash__:

  1. Two model instances compare equal if and only if they share the exact same Options.concrete_model and the same non-null primary key (my_pk == other.pk). That means a "PublishedStory" proxy instance with pk=1 compares True against a "Story" instance with pk=1 — even though their Python classes differ! Two unsaved instances (pk is None) compare equal only by object identity (self is other).
  2. Model.__hash__ hashes Model.pk — and raises TypeError whenever _is_pk_set() is False! Why? Because Python requires an object’s hash never to change while it lives inside a set or dict. If an unsaved "Story()" were hashable before save() assigned its database id, saving it would mutate its hash and silently break every set or dict holding it.

Verify all three properties — adding/db, hash(unsaved), from_db skipping callable defaults, and proxy equality — live in ch06-models:

Recorded on Django 6.1.3 ch06-models script
ModelState, Model.__init__ vs Model.from_db, and identity
  unsaved Story(): adding=True db=None pk=None
  hash(unsaved) -> TypeError: Model instances without primary key value are unhashable
  callable default invocations: Model()=1, Model.from_db(deferred)=0
  PublishedStory(pk=1) == Story(pk=1): True (concrete_model matches)

Where django.db.models.base.ModelState and instantiation leak

Now that we know how a model tracks adding, db, and deferred columns inside _state, let’s trace what happens when you persist that instance back to SQL in Inside Model.save: insert vs. update.