6.3 Models, metaclasses, and state
Attribute access, deferred fields, and relations
Why does reading a deferred attribute or an unjoined foreign key on a model instance trigger a hidden SQL query?
In plain Python, reading "obj.body" or "obj.desk" is a nanosecond dictionary lookup in "obj.__dict__". On a Django Model, that same dot operator can silently open a database cursor and run a "SELECT" — because ModelBase replaced every field on the class with a Python descriptor.
Understanding the three descriptor families — DeferredAttribute, ForwardManyToOneDescriptor, and the collection descriptors (ReverseManyToOneDescriptor / ManyToManyDescriptor) — together with the instance’s relation cache explains both how N+1 query bugs happen and how Django 6.1’s new FetchMode protocol lets you batch or forbid them.
Three descriptor lanes on one "Story" instance
ch06-models. Notice that all lazy database lookups — whether for a deferred text column or an unjoined foreign key — now funnel through one Django 6.1 hook: FetchMode.fetch.DeferredAttribute and ForeignKeyDeferredAttribute
Open DeferredAttribute. Every concrete scalar field on a model ("id", "headline", "body", "status") gets a DeferredAttribute on the class:
class DeferredAttribute:
def __get__(self, instance, cls=None):
if instance is None:
return self
data = instance.__dict__
field_name = self.field.attname
if field_name not in data:
val = self._check_parent_chain(instance)
if val is None:
if not instance._is_pk_set():
raise AttributeError(...)
instance._state.fetch_mode.fetch(self, instance)
if field_name not in data:
raise instance._meta.model.DoesNotExist(...)
else:
data[field_name] = val
return data[field_name]
Look closely at why DeferredAttribute is a non-data descriptor (it defines __get__, not __set__)! In Python’s attribute lookup order, an entry in "instance takes precedence over a non-data descriptor on the class. That means:
- When
"body"was loaded in SQL,"body"sits directly in"instance, so reading.__dict__" "story.body"bypassesDeferredAttributecompletely at pure CPython dict speed!.__get__ - When you loaded the row with
QuerySet.deferorQuerySet.only,Model.__init__simply skipped setting"body"in"instance. Now reading.__dict__" "story.body"falls through toDeferredAttribute, sees.__get__ field_name not in data, and callsFetchMode.fetch. Under defaultFETCH_ONE,DeferredAttributecalls.fetch_one Model, runs a.refresh_from_db(fields=["body"]) "SELECT"for that one column, stores it in"instance, and every subsequent read hits the dict in zero queries!.__dict__['body']"
Now compare ForeignKeyDeferredAttribute, which ForeignKey installs on "desk_id":
class ForeignKeyDeferredAttribute(DeferredAttribute):
def __set__(self, instance, value):
if instance.__dict__.get(self.field.attname) != value and self.field.is_cached(
instance
):
self.field.delete_cached_value(instance)
instance.__dict__[self.field.attname] = value
Because it defines __set__, it becomes a data descriptor — intercepting assignments like "story so that if "story was still holding the old "Desk" object (pk=1), Django immediately evicts the stale relation cache entry before writing the new integer ID!
ForwardManyToOneDescriptor and the relation cache
Open ForwardManyToOneDescriptor, which ForeignKey installs on "desk":
- On
"story.desk",__get__callsFieldCacheMixin— which looks up.get_cached_value "instance. If._state .fields_cache['desk']" select_related("desk"),prefetch_related("desk"), or an earlier read already populated the relation cache, Django returns the cached"Desk"instance with 0 SQL queries. - On a
KeyError, it verifies that the local FK column ("desk_id") is non-null, checks multi-table ancestors if any, and then callsFetchMode.fetch.- Under
FETCH_ONE,ForwardManyToOneDescriptorruns.fetch_one ForwardManyToOneDescriptor(.get_object SELECT ... FROM "newsroom_desk" WHERE "id" = %s) and caches the result in_state. (For a.fields_cache["desk"] OneToOneField, lines 286–287 also pre-populate the reverse cache on the target object so bouncing back doesn’t run a second query!) - Under Django
6.1’sFETCH_PEERS(FetchPeers, covered deeply in Chapter 7),fetch_manycallsprefetch_related_objectsacross every sibling instance loaded in the same queryset! - Under Django
6.1’sFETCH_RAISE, it runs 0 SQL and raisesFieldFetchBlockedimmediately!
- Under
- On assignment (
"story),.desk = metro" __set__(ForwardManyToOneDescriptor, lines 294–395) validates the related instance’s type and database router, copies the target primary key into.__set__ "story, and writes the target object into.__dict__['desk_id']" "story.._state .fields_cache['desk']"
Watch all four behaviors — deferred read, raw "desk_id" read, relation cache hit/invalidation, and FETCH_RAISE — execute live on our newsroom "Story" model:
Descriptors: DeferredAttribute, ForwardManyToOneDescriptor, and FETCH_RAISE
after .defer('body'): deferred=['body'] 'body' in __dict__=False
1st read story.body -> queries=1 len=251 sql=SELECT "newsroom_story"."id", "newsroom_story"."body" FROM "newsroom_story" WHERE "newsroom_story"."id" = %s LIMIT 21
2nd read story.body -> queries=0 'body' in __dict__=True
before story.desk: is_cached=False fields_cache={}
read story.desk_id -> queries=0 value=1
1st read story.desk -> queries=1 desk='Metro' cached_keys=['desk']
2nd read story.desk -> queries=0 (served from _state.fields_cache)
after story.desk_id=2: is_cached=False (ForeignKeyDeferredAttribute invalidated cache)
FETCH_RAISE story.desk -> queries=0 FieldFetchBlocked: Fetching of Story.desk blocked.
Reverse and many-to-many descriptors
Access "desk.stories" (ReverseManyToOneDescriptor, ReverseManyToOneDescriptor) or "story.beats" (ManyToManyDescriptor, lines 1028–1060), and __get__ does not run SQL immediately — instead, it returns a freshly constructed dynamic RelatedManager subclass inheriting from the target model’s default manager class (create_reverse_many_to_one_manager, lines 714–760).
Notice two crucial details inside those descriptors:
- Direct assignment (
"desk) is blocked by.stories = [...]" __set__(TypeError: Direct assignment to the reverse side of a related set is prohibited. Use stories), because silently issuing database.set() instead. "UPDATE"s inside an=statement would hide write side effects. - Calling
"deskinspects.stories .all()" "instancefirst (populated by._prefetched_objects_cache" prefetch_related); calling any additionalQuerySet.filteron it creates a new queryset that ignores the prefetch cache (Chapter 7).
Where model descriptors leak
- Reading
"story.desk.id"instead of"story.desk_id"triggers an unnecessary"SELECT"every time. Unless"desk"was joined viaselect_related,"story.desk"fires a full query just to read the exact integer already sitting in"story..__dict__['desk_id']" - Django templates evaluate descriptors silently in loops. Writing
{{ storyinside a.desk .name }} {% for story in stories %}loop withoutselect_related("desk")fires oneForwardManyToOneDescriptorSQL query per iteration — turn on.__get__ fetch_mode(FETCH_RAISE)in tests or view querysets on Django6.1to catch accidental lazy loads with a loudFieldFetchBlockedtraceback. - Stale
"fields_cache"after mutating a related row elsewhere. If"story.desk"is cached in"_stateand another query updates.fields_cache" "Desk"in SQL,"story.desk"keeps returning the stale Python object until you callModel..refresh_from_db
Every descriptor we just opened reads and writes into one small companion object attached to every instance: django. Next, we inspect how instances are constructed, cached, compared, and hashed in ModelState, instantiation, and from_db.