【发布时间】:2021-04-07 10:42:43
【问题描述】:
所以我正在研究 Django 的多表继承,以及它与 Postgres 的表继承有何不同。
假设我有以下模型:
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)
现在,如果我以此构建数据库,我会得到一个类似于以下内容的表:
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 |
+-------------+---------+-------------+
这不是主意,因为这意味着要获得首都城市的市长,我必须进行 2 次连接,一次从 capitals 到 cities,然后从 cities 到 mayors。
在 Postgres 中,我们可以:
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 | |
+------------+--------------+------------------------------------------------------+
有没有办法在 Django 中使用Postgres' table inheritance?
提前致谢
【问题讨论】:
-
不,Django 不是特定于数据库的,并且某些功能没有实现。 ddl-inherit 也有在使用前应考虑的警告。 Django 功能票可以在这里找到code.djangoproject.com/ticket/24632
-
如果您正在 Django 中寻找单表继承,这张票可能会有所帮助stackoverflow.com/questions/241250/…
-
感谢@iklinac,但我正在寻找多表。我认为必须有人为它构建了一个包,但似乎没有人有,所以我想由我决定构建一个。
标签: django postgresql class-table-inheritance