我有一个问题,我不知道如何在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')
由于
答案 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 ...