【问题标题】:join 2 models through another model which they have a foreign key to it通过另一个具有外键的模型加入 2 个模型
【发布时间】: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 模型上有多行,我的目标是检索连接条件满足的所有行

【问题讨论】:

标签: python django orm outer-join


【解决方案1】:

你可以得到你相关的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()

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

【讨论】:

  • first()函数做什么?
  • 第一个函数只是从数据库中获取第一个对象。将其替换为您需要的方法,例如用于完整列表的 all() 或 get(key=value)。
猜你喜欢
  • 2012-05-02
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 2013-12-11
  • 2011-04-13
相关资源
最近更新 更多