Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 77 ยท Models and the ORM

Model Inheritance and Abstract Models

Share fields and behavior between Django models with abstract base classes, multi-table inheritance, proxy models and mixins, and learn when each one fits.

Sooner or later, several of your models start to look alike. Articles, comments and orders all want a created_at and an updated_at column. A restaurant is a kind of place, so it needs everything a place has plus a few extras. A "paid invoice" is really just an invoice with different default behavior. Copy-pasting those fields works, but you will forget one of the copies the first time you change something.

Django models are ordinary Python classes, so you can use inheritance to share code. The twist is that a model is also a database table, and Django has to decide what an inherited class means for the tables. It offers three answers: abstract base classes (share code, no table for the parent), multi-table inheritance (one table per class, joined together) and proxy models (no new table, only new Python behavior). This lesson explains all three and ends with a rule of thumb for choosing.

If you need a refresher on plain Python inheritance first, read Python inheritance. For the basics of fields and tables see Models and Fields.

flowchart TB
    subgraph A["Abstract base class"]
        direction TB
        A1["TimeStamped<br/>(no table)"] --> A2["Article<br/>table: all fields"]
        A1 --> A3["Note<br/>table: all fields"]
    end
    subgraph M["Multi-table inheritance"]
        direction TB
        M1["Place<br/>table: name, city"] --- M2["Restaurant<br/>table: serves_pizza<br/>+ link to Place"]
    end
    subgraph P["Proxy model"]
        direction TB
        P1["Order<br/>table: orders"] --- P2["OpenOrder<br/>same table"]
    end

Three ways to inherit: the parent has no table, the parent and child each have a table, or parent and child share one table.

Abstract base classes

An abstract base class is a model that exists only to be inherited from. You mark it with abstract = True in its Meta class. Django never creates a table for it and never lets you query it. Each child gets its own table that contains the parent's fields plus its own.

This is the right tool for the "timestamp on everything" problem. The next example defines a TimeStamped base class and two children. We use an in-memory SQLite database and create the tables with the schema editor, the same low-level tool migrations use.

Python An abstract TimeStamped base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the output carefully. There are two tables, shop_article and shop_note, and no TimeStamped table at all. Both children received created_at and updated_at, and TimeStamped.objects does not exist because an abstract model cannot be queried.

Meta inheritance

The second class, Note, shows a detail that surprises many people. If the child does not declare its own Meta, it inherits the parent's Meta (minus abstract). If it does declare one, the parent's options are gone unless you extend it explicitly, as Article did with class Meta(TimeStamped.Meta). That is why Article is ordered newest first and Note has no ordering. Django also resets abstract = False for the child automatically, so children are real models.

Abstract classes often hold relations too, for example an author = ForeignKey(User, ...) shared by many children. If two children point at the same model with the same related_name, their reverse accessors on that model clash and Django reports an error. Use placeholders in related_name:

Python
class Authored(models.Model):
    author = models.ForeignKey(
        "auth.User",
        on_delete=models.CASCADE,
        related_name="%(app_label)s_%(class)s_set",
    )

    class Meta:
        abstract = True

Django replaces %(class)s with the lowercase child class name and %(app_label)s with its app, so each child gets a unique reverse name such as blog_article_set.

Multi-table inheritance

If the parent is not abstract, Django creates a table for the parent and a table for each child. The child's table holds only the child's own fields plus a one-to-one link back to the parent row. This is called multi-table inheritance. It fits the "is-a" relationship: a restaurant is a place, and you want to query all places, restaurants included.

Python Place and Restaurant: two tables, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The restaurant table has only two columns: the place_ptr_id link and serves_pizza. The name and city live in shop_place. Django creates the link automatically; its name is the parent's lowercase name plus _ptr, and it is also the child's primary key. Because of that, restaurant.pk equals the place's id.

Notice what each query sees:

  • Place.objects.count() counts every place, including the restaurant, so it prints 2.
  • Restaurant.objects.count() counts only the child rows (1).
  • From a Place you can reach the child through a lowercase attribute (place.restaurant). If that place has no child row, Django raises Restaurant.DoesNotExist.

The cost of the JOIN

Every query on the child joins the two tables, and every write touches both. For a hierarchy with several levels, the joins add up. Multi-table inheritance is convenient, but it hides real cost, and it is the least used of the three styles in busy projects. Prefer it only when you truly need to query the parent type across all children (for example, "search every place"). If you only want to share fields, use an abstract base class instead. If you want to relate a model to another model loosely, a plain OneToOneField or ForeignKey is more explicit than inheritance and just as easy to query.

Do not override a parent's field in a child model, except for abstract parents. In multi-table inheritance, a child field with the same name as an inherited field raises a field-clash error because both tables would define it.

Proxy models

Sometimes you want different Python behavior on the same data: another default ordering, a custom manager, extra methods. You do not need new columns, so you do not need a new table. A proxy model gives you exactly that. Declare it by subclassing the real model and setting proxy = True.

Python A proxy model with its own manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

OpenOrder has no table of its own: it reads and writes shop_order. But it has a different manager (only open orders), a default ordering by code and a close() method. Saving a proxy instance saves a normal row, so the original Order sees every change. Proxies are cheap, need no migration that changes the schema, and are a clean place to hang behavior that only matters in one context.

Two rules to remember: a proxy must inherit from exactly one concrete (non-abstract) model, and it cannot add new fields. Common uses are:

  • a different ordering or Meta.verbose_name, often to show the same table twice in the admin;
  • a model with a different default manager;
  • extra methods or properties for one feature, without cluttering the main model.

Mixins: sharing behavior without tables

The TimeStamped class above was both a mixin and an abstract model. You can also share behavior only, with a plain Python class that has no fields. A model class can inherit from several parents, but at most one of them may be a concrete model (the others should be abstract models or plain Python classes).

Python
class SlugMixin:
    """Plain Python class: no fields, only behavior."""

    def slug_source(self):
        raise NotImplementedError

    def make_slug(self):
        from django.utils.text import slugify
        return slugify(self.slug_source())


class Post(SlugMixin, TimeStamped):
    title = models.CharField(max_length=100)

    def slug_source(self):
        return self.title

Put mixins to the left of the model base classes so that Python's method resolution order finds the mixin first. A mixin that declares fields must itself be an abstract models.Model subclass, otherwise Django does not see its fields.

Which style should you choose?

Need Use
The same fields or methods on several unrelated models Abstract base class
Query all items of a parent type, children add their own fields Multi-table inheritance (use sparingly)
Same data, different behavior (manager, ordering, methods) Proxy model
Reusable behavior without fields Plain mixin class
Link two different entities ForeignKey or OneToOneField

A good default is to start with abstract base classes for shared fields and use plain relations for everything else. Reach for multi-table inheritance only when you can name the query that needs it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you set abstract = True in a model's Meta class?

    An abstract model only provides fields and methods to its children. Each concrete child gets a complete table of its own, and the abstract model itself cannot be queried.
  2. 2. A Restaurant(Place) model uses multi-table inheritance. How is the relationship stored?

    The child table stores only its own columns and an automatic one-to-one pointer to the parent row. Queries on the child JOIN the two tables.
  3. 3. Which statement about proxy models is true?

    Proxies change only Python-level behavior. They share the concrete model's table and cannot add fields.
  4. 4. A child of an abstract base class defines its own class Meta: without extending the parent's Meta. What happens to the parent's ordering?

    A child that declares its own Meta does not receive the parent's Meta options unless it subclasses it, as in class Meta(Parent.Meta).

Summary

  • Abstract base classes share fields and methods; the parent has no table and each child gets a complete one.
  • A child without its own Meta inherits the parent's; with its own Meta it must extend Parent.Meta explicitly to keep the options.
  • Use %(class)s and %(app_label)s in related_name so children of an abstract class do not clash.
  • Multi-table inheritance creates a table per class, linked by an automatic *_ptr one-to-one key; queries on children use JOINs.
  • Proxy models share the parent's table and change only ordering, managers and methods.
  • Mixins hold behavior without fields; put them before the model base classes.
  • Start with abstract classes and plain relations; use multi-table inheritance only when you must query the parent type.

Next, move from the database layer to user input: Django Forms.