[Fixed]-Django, avoid N+1 query

1👍

You want prefetch_related

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

You can then iterate through the queryset with:

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

You can improve this further by using select_related to fetch the rule.

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

For more information see the prefetch related docs – your models are very similar to those in the examples.

Leave a comment