First of all, inheritance has not a natural translation to relational database architecture (ok, I know, Oracle Type Objects and some other RDBMS support inheritance but django don't take advantage of this functionality)

At this point, notice than django generates new tables to subclasses and write lots of left joins to retrieve data from this 'sub-tables'. And left joins are not your friends. In a high performance scenario, like a game backend or something else, you should avoid it and resolve inheritance 'by hand' with some artifacts like nulls, OneToOne or foreign keys. In OneToOne scenario, you can call the related table directly or only if you need it.

... BUT ...

"In my opinion (TGW)" you should to include model inheritance in your enterprise projects when it catches to your universe of discourse. I do this, and I save a lot of development hours to my customers thanks to this feature. Also, code becomes clean and elegant and that means easy maintenance (notice that this kind of projects don't have hundreds or requests by second)

Question by question

Q: What is wrong with this kind of inheritance in Django?
A: Lot of tables, a lot of left joins.

Q: Why are explicit OneToOneFields better?
A: You can access directly to related model without left joins.

Q: Are there any illustrative examples (benchmarks)?
A: No comparable.

Q: Does not select_related() allow us to control when JOINs are invoked?
A: django joins needed tables.

Q: What are the alternatives to multi-table inheritance when I need to reference a base class in another model?
A: Nullification. OneToOne relations and lots of code lines. It depends on application needs.

Q: Are GenericForeignKeys better in this case?
A: Not for me.

Q: What if I need OneToOneField to base model?
A: Write it. There is no problem with this. For example, you can extend User model, and also you can have a OneToOne to User base model for some users.

Conclusion

You should to know the cost of write and maintenance code without model inheritance also the cost of hardware to support model inheritance applications and act accordingly.

Just a joke: you can write it on assembly code, and it will run faster.

Quoting Trey Hunner:

Your time is usually much more expensive than your CPU's time.

Answer from dani herrera on Stack Overflow
Top answer
1 of 5
36

First of all, inheritance has not a natural translation to relational database architecture (ok, I know, Oracle Type Objects and some other RDBMS support inheritance but django don't take advantage of this functionality)

At this point, notice than django generates new tables to subclasses and write lots of left joins to retrieve data from this 'sub-tables'. And left joins are not your friends. In a high performance scenario, like a game backend or something else, you should avoid it and resolve inheritance 'by hand' with some artifacts like nulls, OneToOne or foreign keys. In OneToOne scenario, you can call the related table directly or only if you need it.

... BUT ...

"In my opinion (TGW)" you should to include model inheritance in your enterprise projects when it catches to your universe of discourse. I do this, and I save a lot of development hours to my customers thanks to this feature. Also, code becomes clean and elegant and that means easy maintenance (notice that this kind of projects don't have hundreds or requests by second)

Question by question

Q: What is wrong with this kind of inheritance in Django?
A: Lot of tables, a lot of left joins.

Q: Why are explicit OneToOneFields better?
A: You can access directly to related model without left joins.

Q: Are there any illustrative examples (benchmarks)?
A: No comparable.

Q: Does not select_related() allow us to control when JOINs are invoked?
A: django joins needed tables.

Q: What are the alternatives to multi-table inheritance when I need to reference a base class in another model?
A: Nullification. OneToOne relations and lots of code lines. It depends on application needs.

Q: Are GenericForeignKeys better in this case?
A: Not for me.

Q: What if I need OneToOneField to base model?
A: Write it. There is no problem with this. For example, you can extend User model, and also you can have a OneToOne to User base model for some users.

Conclusion

You should to know the cost of write and maintenance code without model inheritance also the cost of hardware to support model inheritance applications and act accordingly.

Just a joke: you can write it on assembly code, and it will run faster.

Quoting Trey Hunner:

Your time is usually much more expensive than your CPU's time.

2 of 5
17

The world has changed.

The first thing to note is that the article titled Django gotcha: concrete inheritance was nearly four years old at the time this question was asked; in 2014. Both Django and RDBMs systems have come a long way since then (example mysql 5.0 or 5.1 were the widely used versions and 5.5 general availability was still one month away).

Joins to my left, joins to my right

It is true that multi table inheritance does result in extra joins behind the scenes most of the time. But joins are not evil. It's worth noting that in a properly normalized database, you almost always have to join to fetch all the required data. When proper indexes are used, joins do not include any significant performance penalties.

INNER JOIN vs LEFT OUTER JOIN

This is indeed the case against multi table inheritance, with other approaches it's possible to avoid a costly LEFT OUTER JOIN and do an INNER JOIN instead or perhaps a subquery. But with multi table inheritance you are denied that choice

🌐
Django Forum
forum.djangoproject.com › using django › using the orm
Design Advice: Multi-Table Inheritance vs. Abstract Base Classes - Using the ORM - Django Forum
April 7, 2024 - Hi, all. I’m currently designing a Django application that will serve as an interface for creating, managing, and practicing different types of flashcards, e.g., front and back, multiple-choice, etc. and am considering how to structure my models. Ideally, each type of flashcard will have its own model, e.g., FrontBackFlashcard, MultipleChoiceFlashcard, etc., and will share several basic attributes.
Discussions

When is multi-table inheritance worth using?
We had same use-case, also a catalogue of generic content items with some specific sub-flavours. We were also wary of the query complexity. But we definitely needed everything in one list, so what options are left besides multi-table inheritance? You could add decoration objects; with GenericRelation/ForeignKey or maybe add various m2m relations. Still you be able to add your extra data you need to add additional tables and incur some query complexity. We couldn't come up with something better for our case so now we're using django-polymorphic. So far it's decent but I think it depends on your requirements and architecture. It definitely adds some complexity, not ideal if you code straight from DB. But considering any decent app needs architecture with a caching strategy it becomes a different picture. In our case most of the hot data comes pre-assembled from a redis cache, and the ORM is usually only hit after content cache-miss/invalidation. So we think we can afford to pay a little overhead on multi-table inheritance to have it conceptually correct. I definitely like how our application can mix content subtypes everywhere. There are a few issues of course, like some unsupported ORM features. It's only a few months and we're still optimising so we'll have to see how it holds up. More on reddit.com
🌐 r/django
5
4
April 30, 2015
How to store different payment types using multi-table inheritance in single Order model?
I am currently considering how to best model purchase order-related data for a project that I would like to build and would appreciate any design advice for the following data modeling challenge: Challenge: I would like to unify all purchase order-related data in a single model, e.g., Order. More on forum.djangoproject.com
🌐 forum.djangoproject.com
1
0
November 17, 2023
postgresql - Django Multi Table Inheritance and Preserving Child and Child History - Database Administrators Stack Exchange
Place can have many different one to one fields, that’s why it can have bookstore, restaurant, and hardware store. But can the same place be both a bookstore and a restaurant at the same time? Now ... More on dba.stackexchange.com
🌐 dba.stackexchange.com
Multi-table inheritance - how to use inherited id for relations?
In my project I had 2 different set of models for 2 different reports. TestsReport Values Then I had to create common Report model to unify and speed up some queries. First I used just standard explicit ForeignKey relations from TestsReport and MetricsReport to Report and it works fine, but ... More on forum.djangoproject.com
🌐 forum.djangoproject.com
0
0
December 10, 2024
🌐
DEV Community
dev.to › zachtylr21 › model-inheritance-in-django-m0j
Model Inheritance in Django - DEV Community
August 24, 2020 - I want to discuss each method, which one we chose and why, and some thoughts about our decision in hindsight. Multi-table inheritance is where the superclass, as well as each subclass, map to their own database tables.
🌐
GitHub
github.com › GabLeRoux › django-multitable-inheritance
GitHub - GabLeRoux/django-multitable-inheritance: 💖django sample app to demonstrate model inheritance
As described in the following post Here's what happens when you use Multi Table Inheritance 🚀 · See multitable/models.py for code snippet. Generated using the awesome django-extensions, you should really use this ✌️
Author   GabLeRoux
🌐
O'Reilly
oreilly.com › library › view › django-2-by › 9781788472487 › ac8dc079-4858-4812-8c1e-1531ec8ad1fb.xhtml
Multi-table model inheritance - Django 2 by Example [Book]
May 31, 2018 - To use multi-table inheritance, you have to subclass an existing model. Django will create a database table for both the original model and the sub-model.
Author   Antonio Melé
Published   2018
Pages   526
🌐
Reddit
reddit.com › r/django › when is multi-table inheritance worth using?
r/django on Reddit: When is multi-table inheritance worth using?
April 30, 2015 -

I've often seen warnings against using multi-table inheritance with Django models, and I can understand why - you end up doing queries across two, or multiple, tables instead of one.

But a site I'm planning seems like a good case for it, and I'd like to sense check things...

I'm going to be storing copies of things like Tweets, Flickr photos, Foursquare checkins, etc. Sometimes I'll want to list these mixed together - eg, all of the most recent tweets, photos and checkins, or all of those posted on a single day. So, not as separate lists, but one mixed list of all types in chronological order.

It seems to me that this would be easier with multi-table inheritance. I could have a parent model that's something like:

class Item(models.Model):
    title = models.CharField()
    posted_time = models.DateTimeField()
    ...

And then inherit that for each type, eg:

class Tweet(Item):
    ...

class Photo(Item):
    ...

Then it would be easy to select the most recent items, or those from a particular timeframe, ordered by time, across all different types. But I'm wary... does this sound like a bad idea? Is it still not worth using multi-table inheritance?

Top answer
1 of 4
3
We had same use-case, also a catalogue of generic content items with some specific sub-flavours. We were also wary of the query complexity. But we definitely needed everything in one list, so what options are left besides multi-table inheritance? You could add decoration objects; with GenericRelation/ForeignKey or maybe add various m2m relations. Still you be able to add your extra data you need to add additional tables and incur some query complexity. We couldn't come up with something better for our case so now we're using django-polymorphic. So far it's decent but I think it depends on your requirements and architecture. It definitely adds some complexity, not ideal if you code straight from DB. But considering any decent app needs architecture with a caching strategy it becomes a different picture. In our case most of the hot data comes pre-assembled from a redis cache, and the ORM is usually only hit after content cache-miss/invalidation. So we think we can afford to pay a little overhead on multi-table inheritance to have it conceptually correct. I definitely like how our application can mix content subtypes everywhere. There are a few issues of course, like some unsupported ORM features. It's only a few months and we're still optimising so we'll have to see how it holds up.
2 of 4
3
One good approach to use abstract models for something the Item - this is convenient since it's DRY but doesn't help to write queries across all your models at once. To actually run the queries I'd suggest using a search index - like Elastic or Solr. A search index like this will be very friendly to the commonly named data attributes (title, created, modified, etc) and give you all kinds of advanced search functionality that you'd normally be lacking with a RDBMS.
🌐
Medium
foysalff.medium.com › understanding-django-model-inheritance-b0c38588ebb4
Understanding Django-Advanced Model Inheritance. | by The CodeCrafter | Medium
August 17, 2024 - With multi-table inheritance, each model in the inheritance chain creates its own table in the database. This is useful when you want to extend a model with additional fields but still need to keep the original table.
Find elsewhere
🌐
Django
code.djangoproject.com › ticket › 7623
#7623 (Multi-table inheritance: Add the ability create child instance from existing parent) – Django
As it exists now, multi-table inheritance does not allow for the creation of a child model instance that inherits from an existing parent model instance.
🌐
DEV Community
dev.to › highcenburg › django-model-inheritance-4f3p
Django Model Inheritance - DEV Community
May 8, 2023 - Multi-table inheritance can be created by defining a model that inherits from another model. from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email ...
🌐
Medium
sambyalsandeep31.medium.com › django-model-inheritance-best-practices-147149d9721
Django Model Inheritance Best Practices | by Sandeep Singh Sambyal | Medium
July 7, 2021 - Each table is linked to the other via one-to-one fields. In this code snippet, Country model is the parent, and the Club model is the child. Country model inherits Club model. Multi-table inheritance is also called as “concrete inheritance”, ...
🌐
Django Forum
forum.djangoproject.com › using django › using the orm
How to store different payment types using multi-table inheritance in single Order model? - Using the ORM - Django Forum
November 17, 2023 - I am currently considering how to best model purchase order-related data for a project that I would like to build and would appreciate any design advice for the following data modeling challenge: Challenge: I would like to unify all purchase order-related data in a single model, e.g., Order.
🌐
B-List
b-list.org › weblog › 2023 › dec › 12 › django-model-inheritance
Django's three types of model inheritance - James Bennett
December 12, 2023 - Quite a few third-party Django applications are able to add new features to models through inheriting from abstract bases. Another option is “proxy” inheritance. This is where you subclass another model, and in your child class’ Meta you declare proxy = True. This one is a bit weird, but the idea is you’re augmenting the parent class’ behavior. A proxy subclass uses the same database table ...
🌐
Django
docs.djangoproject.com › en › 4.1 › topics › db › models
Models | Django documentation | Django
December 15, 2022 - If you want to control the name ... back to the parent class. When using multi-table inheritance, a new database table is created for each subclass of a model....
🌐
Codeloop
codeloop.org › home › django multi table model inheritance
Django Multi Table Model Inheritance - Codeloop
March 20, 2024 - All of the fields of Place will also be available in Restaurant, although the data will reside in a different database table. After creating of the models, we need to migrate our project, first you need to do ... You can see that Django created two database models for us.
🌐
Django Forum
forum.djangoproject.com › using django › using the orm
Multi-table inheritance - how to use inherited id for relations? - Using the ORM - Django Forum
December 10, 2024 - In my project I had 2 different set of models for 2 different reports. TestsReport Values Then I had to create common Report model to unify and speed up some queries. First I used just standard explicit ForeignKey relations from TestsReport and MetricsReport to Report and it works fine, but it leads to 3 different set of IDs while just single report ID would be enough.
🌐
Django Forum
forum.djangoproject.com › using django
Using a multi-table inheritance model as a through table - Using Django - Django Forum
July 14, 2021 - I’m trying to use a multi-table inheritance model as a through table, as shown below: class Base(models.Model): ... class Through(Base): ... class RelatedModel(models.Model): ... class Model(models.Model): field = models.ManyToManyField(RelatedModel, through='Base') instance = Model.objects.get(pk=1) related = RelatedModel.objects.get(pk=1) instance.add(related) # ValueError: Can't bulk create a multi-table inherited model However, I keep running into an error when adding a model...
🌐
Schinckel
schinckel.net › 2016 › 04 › 30 › multi-table-inheritance-and-the-django-admin
Multi-table Inheritance and the Django Admin - Schinckel.net
April 30, 2016 - from django import forms from django.conf.urls import url from django.contrib import admin from django.utils.translation import ugettext as _ from .models import Sheep class SubclassFilter(admin.SimpleListFilter): title = _('gender') parameter_name = 'gender' def lookups(self, request, model_admin): return Sheep.SUBCLASS_CHOICES def queryset(self, request, queryset): if self.value(): return queryset.exclude(**{self.value(): None}) return queryset @admin.register(Sheep) class SheepAdmin(admin.ModelAdmin): list_display = [ 'tag_id', 'date_of_birth', 'gender' ] list_filter = [SubclassFilter] def
🌐
LinkedIn
linkedin.com › pulse › mastering-djangos-model-inheritance-ali-ranjbar-mes5f
Mastering Django's Model Inheritance
February 12, 2024 - from django.db import models class ...length=100) Multi-table inheritance creates a one-to-one relationship between a parent model and its child models, with each having its own database table....
🌐
Ilovedjango
ilovedjango.com › django › models-and-databases › model-inheritance
Model Inheritance
I Love Django is an online platform to learn and share knowledge about the Django Web framework.