python - 内连接3个类

时间:2013-12-03 07:39:59

标签: python django django-models inner-join

我有一个问题,我不知道如何在python / django中进行内连接(没有原始sql)...

这是我的课程:

class A(models.Model):
    parameter1 = models.CharField()

class B(models.Model):
    parameter1 = models.CharField()
    a = models.ForeignKey(a)

class C(models.Model):
    parameter1 = models.CharField()
    b = models.ForeignKey(b)

我如何仅使用django获得相同的结果,作为此请求:

query = A.objects.raw('SELECT * FROM A INNER JOIN B ON A.id=B.a_id INNER JOIN C ON B.id=b_id')

由于

1 个答案:

答案 0 :(得分:1)

您可以使用isnull或任何其他字段查找来约束A:

中的数据
q = A.objects.filter(b__isnull=False, b__c__parameter1__isnull=False)

结果查询将与此类似:

SELECT "appname_A"."id", "appname_A"."parameter1" FROM "appname_A"
INNER JOIN "appname_B" ON ("appname_A"."id" = "appname_B"."a_id")
INNER JOIN "appname_C" ON ("appname_B"."id" = "appname_C"."b_id")
WHERE ("appname_C"."parameter1" IS NOT NULL AND "appname_B"."id" IS NOT NULL)
ORDER BY "appname_A"."id" ASC

如果要从联接表中选择一个查询中的所有数据,则应使用select_related中的C向后):

q = C.objects.filter(b__a__parameter1=SOMETHING).select_related()

结果查询将从以下开始:

SELECT "appname_C"."id", "appname_C"."parameter1", "appname_C"."b_id",
       "appname_B"."id", "appname_B"."parameter1", "appname_B"."a_id",
       "appname_A"."id", "appname_A"."parameter1"
INNER JOIN ...