Django内部联接查询集 [英] Django Inner Join Queryset

查看:86
本文介绍了Django内部联接查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django,我需要使用两个内部联接进行查询。

I'm working with Django and I need to do a queryset using two inner joins.

我有三个模型A,B和C,我想在psql中进行如下查询:

I have three models A, B, and C and I want to do a query like the following in psql:

SELECT DISTINCT a FROM A
INNER JOIN B ON B.a_id = A.id
INNER JOIN C ON C.b_id = B.id;

模型:(仅包括相关字段)

Models: (only included relevant fields)

class A(models.Model):
    id = models.IntegerField(primary_key=True)

class B(models.Model):
    id = models.IntegerField(primary_key=True)
    a = models.ForeignKey(A, null=True, blank=True,on_delete=models.SET_NULL)

class C(models.Model):
    b = models.ForeignKey(B, null=True, on_delete=models.SET_NULL)   

因此,C中的所有内容都链接回B中的一件事,B中的所有内容都链接回A中的一件事。我想尝试获取A中所有在C中都有的不同元素。

So everything in C links back to one thing in B and everything in B links back to one thing in A. I want to try and get all the distinct elements in A that have something in C.

如何使用Django queryset做到这一点?谢谢。

How do I do this using django queryset? Thanks.

推荐答案

A.objects.filter(b__c__isnull = False)结果是带有相同结果的sql:

A.objects.filter(b__c__isnull=False) results a sql w/ same result:

SELECT DISTINCT a.* FROM a 
INNER JOIN b ON (a.id = b.a_id)
INNER JOIN c ON (b.id=c.b_id)
WHERE c.id IS NOT NULL;

P.S。为什么要使用 IntegerField 代替 AutoField 作为ID?

P.S. Why do you use IntegerField instead of AutoField for ids?

这篇关于Django内部联接查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆