nested query filter _ Django

余生长醉 提交于 2020-06-17 02:12:05

问题


I keep it simple. I have 3 models.

 class C(models.model):
    some_field = models.BooleanField(default=False)

 class B(models.model):
    b = models.ForeignKey(C)

 class A(models.model):
    a = models.ForeignKey(B)

I need a query filter that gets A.a.b.some_field = True. how can I achieve this ?


回答1:


You can filter your A objects that satisfy this condition with:

A.objects.filter(a__b__some_field=True)

This will generate a query that looks, more or less like:

SELECT a.*
FROM a
JOIN b ON a.a_id = b.id
JOIN c ON b.b_id = c.id
WHERE c.some_field = 1

The double underscore (__) can be used to look "through" relations (like ForeignKeys, OneToOneFields and ManyToManyFields). In case it is ...-to-many field, this is existentially quantified. But here the ForeignKeys are many-to-one relations, so that does not matter.

Note: ForeignKeys to B (or C) is typically named b (or c), not a (or b), since that is the name of the current model. The name of a relation typically specifies how the object(s) it targets relate to the current model.



来源:https://stackoverflow.com/questions/54377931/nested-query-filter-django

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