Django 6.1.3

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

Figure 6.2 Every branch in this plate is verified against 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.__dict__" takes precedence over a non-data descriptor on the class. That means:

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.desk_id = 2" so that if "story._state.fields_cache" 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":

  1. On "story.desk", __get__ calls FieldCacheMixin.get_cached_value — which looks up "instance._state.fields_cache['desk']". If 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.
  2. On a KeyError, it verifies that the local FK column ("desk_id") is non-null, checks multi-table ancestors if any, and then calls FetchMode.fetch.
    • Under FETCH_ONE, ForwardManyToOneDescriptor.fetch_one runs ForwardManyToOneDescriptor.get_object (SELECT ... FROM "newsroom_desk" WHERE "id" = %s) and caches the result in _state.fields_cache["desk"]. (For a 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’s FETCH_PEERS (FetchPeers, covered deeply in Chapter 7), fetch_many calls prefetch_related_objects across every sibling instance loaded in the same queryset!
    • Under Django 6.1’s FETCH_RAISE, it runs 0 SQL and raises FieldFetchBlocked immediately!
  3. On assignment ("story.desk = metro"), __set__ (ForwardManyToOneDescriptor.__set__, lines 294–395) validates the related instance’s type and database router, copies the target primary key into "story.__dict__['desk_id']", and writes the target object into "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:

Recorded on Django 6.1.3 ch06-models script
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:

Where model descriptors leak

Every descriptor we just opened reads and writes into one small companion object attached to every instance: django.db.models.base.ModelState. Next, we inspect how instances are constructed, cached, compared, and hashed in ModelState, instantiation, and from_db.