通过另一个模型加入 2 个模型,他们有一个外键

join 2 models through another model which they have a foreign key to it

我有 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 的每一行,在 temp1 和 temp2 模型上有多行,我的目标是检索满足连接条件的所有行

你可以得到你相关的temp3,然后得到一组引用这个temp3的所有temp2:

t1 = temp1.objects.first()
t3 = t1.temp3
t2_set = t3.temp2_set.all()

或者,在一行中:

t2_set = temp1.objects.first().temp3.temp2_set.all()

但正如 Michael 所说,如果可能,您应该使用 Many2Many 字段。