简体   繁体   中英

Django Inner join Parent model with child model

I have this tables

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

how can join all tables?

I want to perform the equivalent SQL query using django's ORM:

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

Now I have this Django ORM but I want join all table together:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM