Django 6.1.3

6.1 Models, metaclasses, and state

What ModelBase.new builds at import time

What actually happens to a model class dictionary when Python executes a Model subclass definition?

When Python finishes running the indented body of our newsroom’s "Story" model, it hands (name, bases, attrs) to ModelBase — the metaclass of Model. By the time ModelBase.__new__ returns, almost nothing you assigned in the class body still exists in "Story.__dict__" in the form you wrote it.

Dissecting ModelBase.__new__ step by step

Open ModelBase.__new__. Its first guard (lines 103–105) checks parents = [b for b in bases if isinstance(b, ModelBase)]; if parents is empty, it is creating Model itself and delegates directly to type.__new__. For every real model subclass, ModelBase.__new__ executes seven distinct stages:

  1. Split normal attributes from contributables (lines 108–123): ModelBase.__new__ pops "__module__", "__classcell__", and "Meta" out of attrs, then loops over the remaining class attributes calling _has_contribute_to_class (_has_contribute_to_class, line 90: not inspect.isclass(value) and hasattr(value, "contribute_to_class")). Ordinary methods, properties, and nested classes (such as "Story.Status", a TextChoices enum class!) go straight to type.__new__ so Python runs __set_name__ normally. Every Field and Manager instance is held aside in "contributable_attrs" — it is never stored raw in "Story.__dict__".
  2. Locate the owning AppConfig and build Options (lines 125–146): Using Apps.get_containing_app_config, Django derives app_label (raising RuntimeError if a non-abstract model sits outside INSTALLED_APPS without an explicit "Meta.app_label"). It then calls ModelBase.add_to_class with "_meta" and Options(meta, app_label), which attaches Options onto "_meta" and deletes the "Meta" reference.
  3. Synthesize three per-model exception classes (lines 147–192): For every concrete and proxy model, subclass_exception dynamically creates three pickleable exception subclasses attached directly to the model class:
    • "DoesNotExist" subclassing ObjectDoesNotExist — or the parent model’s "DoesNotExist" on concrete inheritance.
    • "MultipleObjectsReturned" subclassing MultipleObjectsReturned.
    • Django 6.1’s "NotUpdated" subclassing both ObjectNotUpdated and DatabaseError so force_update=True or update_fields=... failures can be caught per model while preserving backwards compatibility with except DatabaseError.
  4. Run contribute_to_class on every field and manager (lines 213–214): ModelBase.add_to_class dispatches contribute_to_class on each contributable object. This is the central protocol of Django’s ORM:
    • A scalar field (Field.contribute_to_class, Field.contribute_to_class) registers itself inside Options.add_field, installs DeferredAttribute(self) on the class at its attname, and — whenever choices is set — attaches "get_<name>_display" as a functools.partialmethod bound to Model._get_FIELD_display.
    • A ForeignKey installs three descriptors across two classes: ForeignKeyDeferredAttribute on "desk_id", ForwardManyToOneDescriptor on "desk", and (lazily once the target model is loaded) ReverseManyToOneDescriptor on "Desk.stories"!
    • A ManyToManyField installs ManyToManyDescriptor on both sides.
    • A Manager installs ManagerDescriptor so accessing "Story.objects" works on the class while accessing "story.objects" on an instance raises AttributeError.
  5. Resolve inheritance (lines 224–378): Proxies link to their concrete_model; concrete subclasses synthesize "<parent>_ptr" OneToOneField parent links; abstract base fields are copy.deepcopy-cloned onto the concrete child. (We trace all three in Section 6.7.)
  6. Finalize in ModelBase._prepare (lines 388, 398–451): Abstract models return early at line 386 (resetting attr_meta.abstract = False so subclasses are concrete unless they opt back in!). Concrete and proxy models run ModelBase._prepare:
    • Options._prepare checks whether a primary key was declared; if not, it reads AppConfig.default_auto_field (falling back to DEFAULT_AUTO_FIELD, BigAutoField in our newsroom project) and synthesizes "id" with auto_created=True.
    • If the class has no docstring, lines 422–426 auto-generate "Story(id, headline, ...)" from its field names.
    • If no manager was declared, lines 434–442 attach a default auto-created Manager at "objects" (unless a field is already named "objects", which raises ValueError).
    • Unnamed "Meta.indexes" receive deterministic names via set_name_with_model, and class_prepared fires.
  7. Register in the app registry (line 389): Apps.register_model stores the class in all_models[app_label][model_name] and flushes any pending lazy_related_operation callbacks waiting on string foreign keys like "StoryBeat".

Watching the transformation live on our newsroom model

Inspect "Story.__dict__" and "Desk.__dict__" right after Django 6.1.3 boots our newsroom app:

Recorded on Django 6.1.3 ch06-models script
ModelBase.__new__: what Story.__dict__ actually contains at runtime
  'Meta' in Story.__dict__: False
  Story.__dict__['id'                ] -> DeferredAttribute
  Story.__dict__['headline'          ] -> DeferredAttribute
  Story.__dict__['desk_id'           ] -> ForeignKeyDeferredAttribute
  Story.__dict__['desk'              ] -> ForwardManyToOneDescriptor
  Story.__dict__['beats'             ] -> ManyToManyDescriptor
  Story.__dict__['objects'           ] -> ManagerDescriptor
  Story.__dict__['get_status_display'] -> partialmethod
  Desk.__dict__['stories']             -> ReverseManyToOneDescriptor
  synthesized exceptions: DoesNotExist(ObjectDoesNotExist), MultipleObjectsReturned(MultipleObjectsReturned), NotUpdated(ObjectNotUpdated, DatabaseError)
  auto-generated __doc__: 'Story(id, headline, slug, body, priority, status, published_at, desk, reporter, edition)'

Every single piece of that trace confirms the metaclass rewrite: "Meta" is gone, every field has vanished behind a descriptor, one "ForeignKey" turned into "desk_id" + "desk" + "Desk.stories", "status" grew "get_status_display", three per-model exception subclasses appeared, and even "Story.__doc__" was synthesized for you.

Where the metaclass leaks

Every field stripped from the class body now lives inside "_meta". Next, we open django.db.models.options.Options and see how fields translate between Python values, SQL column types, and migration blueprints in Options, fields, and column metadata.