【问题标题】:Django Inner join Parent model with child modelDjango Inner 将父模型与子模型连接起来
【发布时间】: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


    【解决方案1】:
      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
    

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 2018-06-17
      • 2020-11-08
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 2019-09-17
      • 2016-06-21
      相关资源
      最近更新 更多