django - Django多表继承不同于Postgres表继承
问题描述
所以我正在研究 Django 的多表继承,以及它与 Postgres 的表继承有何不同。
假设我有以下型号:
模型.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
to cities
,然后从cities
to 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 的表继承?
提前致谢
解决方案
不幸的是,这在 Django 本身和任何 3rd 方包中都没有实现。如果不对 Django 的核心进行一些重大更改,甚至可能无法创建第 3 方包。
如果你对这个特性感兴趣,在 Django 的 bug tracker 中有一张关于这个确切特性的票。
请记住,这种类型的继承确实有一些主要限制,例如指向父表的外键无法处理子实例,索引在父子之间不共享(没有开箱即用的唯一性跨越解决方案在父表和所有子表之间)等。
推荐阅读
- html - li 作为多个 li 在 ul 内部的主要容器不起作用
- c# - C# 线程和多用户程序
- ms-access - Access VBA - 用不同的记录源分隔相同的表单?
- python - 配准具有不同视野的非各向同性 CT 扫描
- python - 在python中定义数组时出现语法错误
- excel - 遍历所有行并找到活动工作表 VBA 的空行
- bootstrap-4 - 使用行/容器引导程序填充窗口剩余高度
- python - 如何在运行 selenium 时在 mac 上粘贴剪贴板中的文本 - Python
- java - 从 (RSA) PublicKey 手动创建 JWK
- azure - 从门户更改 Azure Api 管理中的服务结构终结点端口