Django 6.1.3

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.__new__, 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.db.transaction.atomic
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.__new__ does at lines 329–349 and 380–386:

  1. The abstract base itself never runs ModelBase._prepare and never calls Apps.register_model — no table exists for it, and trying to instantiate it raises TypeError("Abstract models cannot be instantiated.") (Model.__init__, line 509). Notice also lines 384–385: Django resets attr_meta.abstract = False on the abstract class’s Meta so that a subclass inheriting class Meta(Parent.Meta): becomes concrete automatically unless it explicitly sets abstract = True again!
  2. When a concrete child subclasses an abstract base, lines 333–340 loop over every field on the abstract parent, call copy.deepcopy(field), and install the fresh copy directly onto the child via add_to_class. (Remember why copy.deepcopy is mandatory: every django.db.models.Field stores self.model = cls!)
  3. At runtime, the child’s "_meta.parents" is {} and its local_fields contain 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.__new__ builds a completely different structure at lines 295–328 and Options._prepare:

  1. Django checks that no local field name clashes with any parent field (raising FieldError if one does).
  2. Unless you declared your own OneToOneField(..., parent_link=True), lines 301–325 synthesize an automatic OneToOneField named "<parent>_ptr" ("story_ptr" with column "story_ptr_id", on_delete=CASCADE, auto_created=True, parent_link=True), and Options._prepare promotes "story_ptr" to be the child table’s primary key (primary_key=True)!
  3. Every "SELECT" on the child table must perform an INNER JOIN against the parent table ("newsroom_investigativestory" INNER JOIN "newsroom_story" ON ("story_ptr_id" = "newsroom_story"."id")) just to hydrate the parent’s columns!
  4. Every save() wraps both tables inside transaction.atomic(savepoint=False) (Model.save_base, lines 984–985), saving the parent row first in Model._save_parents, copying the parent’s newly generated PK into "story_ptr_id", and then saving the child table in Model._save_table.
  5. Every delete() cascades both ways: deleting a parent cascades to the child via on_delete=CASCADE, and deleting a child recursively collects and deletes the parent row unless you pass keep_parents=True (Collector.collect, lines 316–330)!

3. Proxy models: alternate Python facade, identical SQL table

Now look at our newsroom’s "PublishedStory" (class PublishedStory(Story): with Meta.proxy = True and a custom manager filtering status="published"). Inside ModelBase.__new__ lines 225–248 and Options.setup_proxy:

  1. Django verifies the proxy has exactly one non-abstract model ancestor (and no abstract ancestors containing concrete fields — a proxy cannot add database columns!).
  2. Options.setup_proxy copies the target’s Options.pk and Options.db_table ("newsroom_story"), sets proxy_for_model = target, sets concrete_model = target._meta.concrete_model, and records _meta.parents[Story] = None.
  3. Options.can_migrate returns False for 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:

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

We have now opened every piece of a Django model: metaclass construction, _meta options, descriptors, django.db.models.base.ModelState, 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.