当没有创建向后关系时,Django多个SQL连接(related_name =' +')?

时间:2017-04-12 14:26:27

标签: python mysql sql django join

我需要使用Django的ORM执行这个SQL语句(见下文)。我加入了3个Django模型。

这是我的SQL要求:

select a.attr_a, c.attr_c
from table_a as a 
left join table_b as b on a.a_id = b.a_id and b.d_id = 1
left join table_c as c on a.a_id = c.a_id and c.d_id = 2
where b.attr_b = 'foo' and c.attr_c = 'bar'

然后是我的Django模型:

class A(models.Model):
    a_id = models.AutoField(primary_key=True)
    attr_a = models.CharField(max_length=250)

class Meta:
    db_table = 'table_a'


class B(models.Model):
    b_id = models.AutoField(primary_key=True)
    attr_b = models.CharField(max_length=250)

    fk_to_a = models.ForeignKey(A, related_name='+')
    fk_to_d = models.ForeignKey(D, related_name='+')

    class Meta:
        db_table = 'table_b'


class C(models.Model):
    c_id = models.AutoField(primary_key=True)
    attr_c = models.CharField(max_length=250)

    fk_to_a = models.ForeignKey(A, related_name='+')
    fk_to_d = models.ForeignKey(D, related_name='+')

    class Meta:
        db_table = 'table_c'


class D(models.Model):
    d_id = models.AutoField(primary_key=True)
    attr_d = models.CharField(max_length=250)

    class Meta:
        db_table = 'table_d'

有没有办法通过单个Django ORM查询来解决这个问题?否则,你能告诉我怎么样吗?

0 个答案:

没有答案