嵌套查询过滤器_ Django [英] nested query filter _ Django

查看:129
本文介绍了嵌套查询过滤器_ Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保持简单。我有3个模型。

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)

我需要一个查询过滤器,该过滤器的Aabsome_field = True。我该如何实现?

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

推荐答案

您可以过滤 A 对象满足以下条件的情况:

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

双下划线( __ )可用于查找直通关系(例如 ForeignKey s, OneToOneField s和 ManyToManyField s)。如果是...- to-many字段,则存在进行量化。但是这里 ForeignKey 是多对一的关系,所以没关系。

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.


注意 ForeignKey B (或 C )通常命名为 b (或 c ),而不是 a (或 b ),因为这是当前模型的名称。关系的名称通常指定其目标对象与当前模型的关系。

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.

这篇关于嵌套查询过滤器_ Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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