[英]Django Inner join Parent model with child model
我有这张桌子
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()
a = Child1.object.select_related('parent').query.sql_with_params()
b = Child2.object.select_related('parent').query.sql_with_params()
c = Child3.object.select_related('parent', 'other_table').query.sql_with_params()
result = a | b | c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.