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 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. 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 executes seven distinct stages:
- Split normal attributes from contributables (lines 108–123):
ModelBasepops.__new__ "__module__","__classcell__", and"Meta"out ofattrs, then loops over the remaining class attributes calling_has_contribute_to_class(_has_contribute_to_class, line 90:not inspect). Ordinary methods, properties, and nested classes (such as.isclass(value) and hasattr(value, "contribute_to_class") "Story.Status", aTextChoicesenum class!) go straight totype.__new__so Python runs__set_name__normally. EveryFieldandManagerinstance is held aside in"contributable_attrs"— it is never stored raw in"Story.__dict__". - Locate the owning
AppConfigand buildOptions(lines 125–146): UsingApps, Django derives.get_containing_app_config app_label(raisingRuntimeErrorif a non-abstract model sits outsideINSTALLED_APPSwithout an explicit"Meta.app_label"). It then callsModelBasewith.add_to_class "_meta"andOptions(meta, app_label), which attachesOptionsonto"_meta"and deletes the"Meta"reference. - Synthesize three per-model exception classes (lines 147–192): For every concrete and proxy model,
subclass_exceptiondynamically creates three pickleable exception subclasses attached directly to the model class:"DoesNotExist"subclassingObjectDoesNotExist— or the parent model’s"DoesNotExist"on concrete inheritance."MultipleObjectsReturned"subclassingMultipleObjectsReturned.- Django
6.1’s"NotUpdated"subclassing bothObjectNotUpdatedandDatabaseErrorsoforce_update=Trueorupdate_fields=...failures can be caught per model while preserving backwards compatibility withexcept DatabaseError.
- Run
contribute_to_classon every field and manager (lines 213–214):ModelBasedispatches.add_to_class contribute_to_classon each contributable object. This is the central protocol of Django’s ORM:- A scalar field (
Field,.contribute_to_class Field) registers itself inside.contribute_to_class Options, installs.add_field DeferredAttribute(self)on the class at itsattname, and — wheneverchoicesis set — attaches"get_<name>_display"as afunctoolsbound to.partialmethod Model.._get_FIELD_display - A
ForeignKeyinstalls three descriptors across two classes:ForeignKeyDeferredAttributeon"desk_id",ForwardManyToOneDescriptoron"desk", and (lazily once the target model is loaded)ReverseManyToOneDescriptoron"Desk.stories"! - A
ManyToManyFieldinstallsManyToManyDescriptoron both sides. - A
ManagerinstallsManagerDescriptorso accessing"Story.objects"works on the class while accessing"story.objects"on an instance raisesAttributeError.
- A scalar field (
- Resolve inheritance (lines 224–378): Proxies link to their
concrete_model; concrete subclasses synthesize"<parent>_ptr"OneToOneFieldparent links; abstract base fields arecopy.deepcopy-cloned onto the concrete child. (We trace all three in Section 6.7.) - Finalize in
ModelBase(lines 388, 398–451): Abstract models return early at line 386 (resetting._prepare attr_metaso subclasses are concrete unless they opt back in!). Concrete and proxy models run.abstract = False ModelBase:._prepare Options._preparechecks whether a primary key was declared; if not, it readsAppConfig(falling back to.default_auto_field DEFAULT_AUTO_FIELD,BigAutoFieldin our newsroom project) and synthesizes"id"withauto_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
Managerat"objects"(unless a field is already named"objects", which raisesValueError). - Unnamed
"Meta.indexes"receive deterministic names viaset_name_with_model, andclass_preparedfires.
- Register in the app registry (line 389):
Appsstores the class in.register_model all_models[app_label][model_name]and flushes any pendinglazy_related_operationcallbacks 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:
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
- Importing a model module before
django.setup()or outsideINSTALLED_APPScrashes immediately. BecauseModelBaseruns at Python class-definition time (inside.__new__ import) and callsApps, importing a model before.get_containing_app_config INSTALLED_APPSis loaded — or placing a concrete model in a module whose app is missing fromINSTALLED_APPS— raisesRuntimeErrorimmediately. - Replacing a field attribute after class creation bypasses
contribute_to_class. Writing"Storyafter the.extra = CharField(...)" classblock merely drops a baredjangoobject onto.db .models .CharField "Story.__dict__";"_meta"never learns about it and queries will ignore it. Dynamic fields must go throughModelBase(or be declared in the class body)..add_to_class - Custom objects with a
contribute_to_classmethod get intercepted. Because_has_contribute_to_classchecks onlynot inspect, any third-party descriptor instance defining that method name is invoked by.isclass(value) and hasattr(value, "contribute_to_class") ModelBaserather than assigned normally.
Every field stripped from the class body now lives inside "_meta". Next, we open django and see how fields translate between Python values, SQL column types, and migration blueprints in Options, fields, and column metadata.