【发布时间】:2017-05-24 07:46:18
【问题描述】:
我有 3 个模型 temp1、temp2、temp3,其中 temp1 和 temp2 具有 temp3.id 的外键。这意味着 temp1 和 temp2 通过 temp3.id 关联。
Class temp1(models.Model):
temp3 = models.ForeignKey('temp3', verbose_name=u"temp3", null=True, blank=True)
i_y = models.IntegerField('i_Y',null=True, blank=True)
iq = models.FloatField('IQ', null=True, blank=True)
class temp2(models.Model):
temp3 = models.ForeignKey('temp3', verbose_name=u"temp3", null=True, blank=True)
q_y = models.IntegerField('Y', null=True, blank=True)
eq = models.IntegerField('EQ', null=True, blank=True)
q_c = models.CharField('category', max_length=1000, null=True, blank=True)
class temp3(models.Model):
title = models.CharField(_('Title'), max_length=400, null=True, blank=True)
如何使用 django ORM 对 temp1 和 temp2 模型进行完全外连接? 事实上,我想用 Django ORM 做一个这样的 sql 查询:
select temp3.title, temp1.i_y, temp1.iq, temp2.eq,temp2.q_c, temp2.q_y from (select temp1.i_y, temp1.iq, temp1.temp3_id AS first_table_id,temp2.temp3_id AS second_table_id,temp2.eq, temp2.q_c, temp2.q_y from temp1 full outer join temp2 on (temp1.temp3_id = temp2.temp3_id AND temp1.i_y = temp2.q_y)) AS t left outer join temp3 (t.first_table_id = temp3.id OR t.second_table_id = temp3.id)
我应该提到,对于 temp3 的每一行,在 db 中的 temp1 和 temp2 模型上有多行,我的目标是检索连接条件满足的所有行
【问题讨论】:
-
为什么不使用 ManyToManyFields 和though 参数。它会更容易使用,因为 django 默认在其 ORM 中提供了许多查询集docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many
标签: python django orm outer-join