So I'm looking at Django's multitable inheritance, and how it differs from Postgres' table inheritance.
Say I have the following models:
models.py
class Mayor(models.Model):
name = models.CharField(max_length=255)
class City(models.Model)
name = models.CharField(max_length=255)
mayor = models.ForeignKey(Mayor, on_delete=models.CASCADE)
class Capital(City):
embassy = models.BooleanField(default=False)
Now, if I build the db from this, I get a table that looks something like:
cities:
+----------+------------------------+---------------------------------------------------------+
| Column | Type | Modifiers |
|----------+------------------------+---------------------------------------------------------|
| id | integer | not null default nextval('main_city_id_seq'::regclass) |
| name | character varying(255) | not null |
| mayor_id | integer | not null |
+----------+------------------------+---------------------------------------------------------+
capitals
+-------------+---------+-------------+
| Column | Type | Modifiers |
|-------------+---------+-------------|
| city_ptr_id | integer | not null |
| has_embassy | boolean | not null |
+-------------+---------+-------------+
This isn't idea, as it means that to get capital cities' mayors, I have to do 2 joins, one from capitals
to cities
, and then from cities
to mayors
.
In Postgres, we can have:
cities:
+------------+-------------+------------------------------------------------------+
| Column | Type | Modifiers |
|------------+-------------+------------------------------------------------------|
| id | integer | not null default nextval('cities_id_seq'::regclass) |
| name | text | |
| mayor_id | realinteger | |
+------------+-------------+------------------------------------------------------+
where the below table is listed as a 'child'
capitals:
+------------+--------------+------------------------------------------------------+
| Column | Type | Modifiers |
|------------+--------------+------------------------------------------------------|
| id | integer | not null default nextval('cities_id_seq'::regclass) |
| name | text | |
| mayor_id | realinteger | |
| embassy | bool | |
+------------+--------------+------------------------------------------------------+
Is there a way to use Postgres' table inheritance inside Django?
Thanks in advance
Unfortunately, this is not implemented neither in Django itself nor in any 3rd party package. It may be even impossible to create a 3rd party package without some major changes to Django's core.
If you are interested in this feature, there is a ticket in Django's bug tracker about this exact feature.
Remember that this type of inheritance does have some major limitations, like foreign keys pointing to the parent table can't handle child instances, indexes are not shared between parent and children (there is no out-of-the-box solution for uniqueness spanned between parent and all children tables) etc.