6.7 Models, metaclasses, and state
Abstract bases, multi-table joins, and proxies
What database tables and SQL joins do abstract models, multi-table inheritance, and proxy models actually create?
In Python, class Child(Parent) looks identical regardless of what Meta says. Inside ModelBase, however, Django splits model inheritance into three completely different database architectures — abstract model inheritance, multi-table inheritance, and proxy model inheritance — with drastically different tables, SQL joins, and write costs.
Comparing all three architectures side by side
Style (Meta flag) |
Tables & "_meta.parents" |
SQL "SELECT" |
SQL "INSERT" / "UPDATE" |
|---|---|---|---|
Abstract model (abstract = True) |
Tables & "_meta.parents" Child table only; fields deep-copied (parents={}) |
SQL "SELECT" Single table, 0 joins |
SQL "INSERT" / "UPDATE" 1 table (1 query) |
| Multi-table (both concrete) | Tables & "_meta.parents" Both tables linked via <parent>_ptr_id PK+FK |
SQL "SELECT" INNER JOIN on every read |
SQL "INSERT" / "UPDATE" 2 tables inside django |
Proxy model (proxy = True) |
Tables & "_meta.parents" Parent table shared (parents={Parent: None}) |
SQL "SELECT" Single table, 0 joins |
SQL "INSERT" / "UPDATE" 1 table (1 query) |
1. Abstract models: compile-time field copying
Declare abstract = True inside "class Meta", and look at what ModelBase does at lines 329–349 and 380–386:
- The abstract base itself never runs
ModelBaseand never calls._prepare Apps— no table exists for it, and trying to instantiate it raises.register_model TypeError("Abstract models cannot be instantiated.")(Model.__init__, line 509). Notice also lines 384–385: Django resetsattr_metaon the abstract class’s.abstract = False Metaso that a subclass inheritingclass Meta(Parentbecomes concrete automatically unless it explicitly sets.Meta): abstract = Trueagain! - When a concrete child subclasses an abstract base, lines 333–340 loop over every field on the abstract parent, call
copy, and install the fresh copy directly onto the child via.deepcopy(field) add_to_class. (Remember whycopy.deepcopyis mandatory: everydjangostores.db .models .Field self.model = cls!) - At runtime, the child’s
"_meta.parents"is{}and itslocal_fieldscontain the copied parent fields natively — zero joins, zero extra tables, and zero runtime inheritance tax.
2. Multi-table inheritance: hidden OneToOneField and automatic INNER JOIN
Subclass a concrete model (class InvestigativeStory(Story):) without proxy = True, and ModelBase builds a completely different structure at lines 295–328 and Options._prepare:
- Django checks that no local field name clashes with any parent field (raising
FieldErrorif one does). - Unless you declared your own
OneToOneField(..., parent_link=True), lines 301–325 synthesize an automaticOneToOneFieldnamed"<parent>_ptr"("story_ptr"with column"story_ptr_id",on_delete=CASCADE,auto_created=True,parent_link=True), andOptions._preparepromotes"story_ptr"to be the child table’s primary key (primary_key=True)! - Every
"SELECT"on the child table must perform anINNER JOINagainst the parent table ("newsroom_investigativestory" INNER JOIN "newsroom_story" ON ("story_ptr_id" = "newsroom_story"."id")) just to hydrate the parent’s columns! - Every
save()wraps both tables insidetransaction(.atomic(savepoint=False) Model.save_base, lines 984–985), saving the parent row first inModel, copying the parent’s newly generated PK into._save_parents "story_ptr_id", and then saving the child table inModel.._save_table - Every
delete()cascades both ways: deleting a parent cascades to the child viaon_delete=CASCADE, and deleting a child recursively collects and deletes the parent row unless you passkeep_parents=True(Collector, lines 316–330)!.collect
3. Proxy models: alternate Python facade, identical SQL table
Now look at our newsroom’s "PublishedStory" (class PublishedStory(Story): with Meta and a custom manager filtering status="published"). Inside ModelBase lines 225–248 and Options:
- Django verifies the proxy has exactly one non-abstract model ancestor (and no abstract ancestors containing concrete fields — a proxy cannot add database columns!).
Optionscopies the target’s.setup_proxy Options.pkandOptions.db_table("newsroom_story"), setsproxy_for_model = target, setsconcrete_model = target, and records._meta .concrete_model _meta..parents[Story] = None Optionsreturns.can_migrate Falsefor proxy models (options.py, line 400): migrations create no new table (only permissions/content-type entries!). Queries against"PublishedStory"hit"newsroom_story"directly with zero joins, while letting you attach a different default manager, default ordering, Python methods, or separate Django Admin registration!
Inspect all three inheritance shapes and their exact SQL live on Django 6.1.3:
Model inheritance: abstract, multi-table parent_link, and PublishedStory proxy
PublishedStory proxy=True db_table='newsroom_story' concrete=Story
PublishedStory.objects.all() JOINs=False WHERE="newsroom_story"."status" = published ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
AbstractChild: parents={} local_fields=['id', 'source_tag', 'title']
InvestigativeStory (MTI): ptr='story_ptr' pk=True parent_link=True has_INNER_JOIN=True
InvestigativeStory SQL FROM: "newsroom_investigativestory" INNER JOIN "newsroom_story" ON ("newsroom_investigativestory"."story_ptr_id" = "newsroom_story"."id") ORDER BY "newsroom_story"."priority" ASC, "newsroom_investigativestory"."story_ptr_id" ASC
Where model inheritance leaks
- Multi-table inheritance turns every list view and every write into a multi-table join and multi-statement transaction. Worse, querying the parent model (
"Story) returns plain.objects .all()" "Story"instances, not"InvestigativeStory"subclasses — forcing polymorphic downcasting viaselect_related("investigativestory")or extra queries per row. Prefer an abstract base class (when tables are independent) or an explicitOneToOneFieldprofile table (when extra columns are optional) unless you truly need shared parent foreign keys. - Signals on a concrete model do not match a proxy sender automatically. Remember
Model.save_baseline 977:pre_saveandpost_savepasssender=origin("PublishedStory"), not"Story"! A signal receiver connected withsender=Storywill silently miss"PublishedStoryand.objects .create(...)" "published_storycalls!.save()" - Forgetting
"%(app_label)s_%(class)s"interpolation in abstractrelated_nameor constraint names causes reverse-accessor clashes. Whenever two concrete models inherit aForeignKeyorUniqueConstraintfrom the same abstract base, Django interpolates%(app_label)sand%(class)sinsideOptions— without those placeholders, both child models fight over the same reverse name or database constraint name.._format_names
We have now opened every piece of a Django model: metaclass construction, _meta options, descriptors, django, save(), Collector cascades, and inheritance. Models describe single rows and their relationships; asking the database for sets of rows, chaining filters without touching SQL, and beating N+1 queries belong to QuerySets and laziness.