Django,避免N + 1查询

尤金

我正在使用三种模型,并希望避免进行N + 1查询。

class Rule(models.Model):

    pass


class RuleConstraint(models.Model):

    rules = models.ManyToManyField(Rule)


class Foo(models.Model):

    rule = models.ForeignKey(Rule, related_name='foos')

对于给定的foo,我可以获得类似以下的相关RuleConstraints

RuleContraint.objects.filter(rules__foos=foo)

问题是,当我没有foos一个foo时,如何避免N + 1查询症状

即,有没有比这更好的方法

for foo in foos:
  rule_constraints = RuleConstraint.objects.filter(rules__foos=foo)
阿拉斯代尔

你要 prefetch_related

foos = Foo.objects.prefetch_related('rule__rule_constraint')

然后,您可以使用以下命令遍历查询集:

for foo in foos:
    rule_constraints = foo.rule.ruleconstraint_set.all()

您可以使用select_related来获取进一步改进rule

foos = Foo.objects.select_related('rule').prefetch_related('rule__rule_constraint')

有关更多信息,请参见预取相关文档-您的模型与示例中的模型非常相似。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章