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 (holding column values like "id", "headline", "desk_id") and a tiny companion object at "instance, an instance of ModelState.
Inside django.db.models.base.ModelState : lazy descriptors to save per-row memory
Open django/ 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!
- On a freshly constructed
ModelState(), its instance dictionary ("__dict__") starts completely empty:db(None),adding(True), andpeers(()) are inherited as class attributes without allocating instance keys. - Even
fields_cacheandfetch_modeare lazy descriptors! Django does not allocate a{}dictionary forfields_cacheon a single instance until some relation is actually cached or inspected. - In Django
6.1,ModelStategainedfetch_modeandpeers(a tuple ofweakref.refhandles to sibling rows fetched in the sameFETCH_PEERSqueryset). Look atModelState(lines 491–495): it explicitly pops.__getstate__ "peers"before pickling because weak references cannot be serialized!
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__:
- The positional fast path (
if not kwargs:, lines 524–533): Zips positionalargsstraight acrossOptionsand calls.concrete_fields setattr(self, field— skipping every entry equal to.attname, val) DEFERRED, a module-level sentinel object! Because every concrete field receives either its SQL value orDEFERRED, the trailingfor field in fields_iter:loop never executes a single iteration andFieldis never called..get_default - The keyword path (
else:, lines 534–613): WalksOptions.fields, checks for duplicate positional+keyword arguments, pops bothField.name(related instances) andField.attname("_id"integers) fromkwargs, callsFieldfor every omitted concrete field, and validates leftover keys against.get_default _property_namesand virtual fields before raisingTypeErroron 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:
- Zero wasted default computations on
QuerySet.defer/QuerySet.onlyrows: If a model declarestoken = CharField(default=generate_expensive_uuid)and a query defers"token",Model.from_dbplacesDEFERREDinto that positional slot soModel.__init__skips the slot without invoking the default callable. - Nearly 2× faster row hydration: Calling
cls(*values)hits the positional fast path instead of dictionary popping and default resolution.
Measure both effects — and the hidden cost of a single post_init signal receiver — live on Django 6.1.3:
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__:
- Two model instances compare equal if and only if they share the exact same
Optionsand the same non-null primary key (.concrete_model my_pk == other). That means a.pk "PublishedStory"proxy instance withpk=1comparesTrueagainst a"Story"instance withpk=1— even though their Python classes differ! Two unsaved instances (pk is None) compare equal only by object identity (self is other). Model.__hash__hashesModel.pk— and raisesTypeErrorwhenever_is_pk_set()isFalse! Why? Because Python requires an object’s hash never to change while it lives inside asetordict. If an unsaved"Story()"were hashable beforesave()assigned its databaseid, saving it would mutate its hash and silently break everysetordictholding it.
Verify all three properties — adding/db, hash(unsaved), from_db skipping callable defaults, and proxy equality — live in ch06-models:
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
- Attaching
pre_initorpost_initsignals to high-volume models silently taxes every queryset. Even a no-oppost_initlistener slowsModel.from_dbby+22%on every row returned by"SELECT"queries. OverrideModel.from_dbdirectly if you need to snapshot field values on load, or compute lazily on access. - Putting a model instance with an explicit/auto PK into a
setbefore cloning it (obj). Remember how Django recommends copying a row: setting both.pk = None; obj ._state .adding = True obj.pk = Noneandobj! If you forget._state .adding = True _stateon a model whose PK has a default (like.adding = True django),.db .models .UUIDField Model.savebehaves differently — which brings us directly to howsave()decides between"INSERT"and"UPDATE". - Two Python instances of the same database row do NOT share state. Unlike SQLAlchemy’s identity map, Django has no session-wide object cache: calling
"Storytwice returns two distinct Python objects (.objects .get(pk=1)" s1 == s2isTrue,s1 is s2isFalse), and mutating"s1.headline"does not update"s2.headline".
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.