【发布时间】:2022-01-07 00:17:45
【问题描述】:
我有这张桌子
class OtherTable(models.Model):
#some attributes
class Parent(models.Model):
#some attributes
class Child1(models.Model):
parent = models.ForeignKey(Parent)
#more attributes
class Child2(models.Model):
parent = models.ForeignKey(Parent)
#more attributes
class Child3(models.Model):
parent = models.ForeignKey(Parent)
other_table = models.ForeignKey(OtherTable)
#more attributes
如何连接所有表?
我想使用 django 的 ORM 执行等效的 SQL 查询:
select *
from parent
inner join child1 on parent.id = child1.parent_id
inner join child2 on parent.id = child2.parent_id
inner join child3 on parent.id = child3.parent_id
inner join othertable on other.id = child3.other_table_id
现在我有了这个 Django ORM,但我想将所有表连接在一起:
Child1.object.select_related('parent').query.sql_with_params()
Child2.object.select_related('parent').query.sql_with_params()
Child3.object.select_related('parent', 'other_table').query.sql_with_params()
【问题讨论】:
标签: python django django-orm