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