gpt4 book ai didi

django - 嵌套查询过滤器_Django

转载 作者:行者123 更新时间:2023-12-05 04:02:23 25 4
gpt4 key购买 nike

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

 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)

我需要一个获取 A.a.b.some_field = True 的查询过滤器。我怎样才能做到这一点?

最佳答案

您可以过滤满足此条件的 A 对象:

A.objects.filter(<b>a__b__some_field=True</b>)

这将生成一个看起来或多或少像这样的查询:

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

双下划线 (__) 可用于“透视”关系(如 ForeignKeyOneToOneField ManyToManyField)。如果它是...对多字段,这是存在量化的。但这里的 ForeignKey 是多对一关系,所以这无关紧要。

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 - 嵌套查询过滤器_Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54377931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com