Django Inner Join Queryset

扶醉桌前 提交于 2019-12-06 17:56:16

问题


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

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)   

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.

How do I do this using django queryset? Thanks.


回答1:


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. Why do you use IntegerField instead of AutoField for ids?



来源:https://stackoverflow.com/questions/17375997/django-inner-join-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!