我是一位有用的助手,可以为您翻译文本。
现在,如果我按照这个构建数据库,得到的表格大致如下:
这不是一个理想的方法,因为这意味着要获取首都市长,我需要进行两次连接,一次从
在Postgres中,我们可以这样做:
所以我正在研究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 |
+-------------+---------+-------------+
这不是一个理想的方法,因为这意味着要获取首都市长,我需要进行两次连接,一次从
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的表继承?
提前致谢