Query Inside Loop (ARCH2064)
Esta página aún no está disponible en tu idioma.
Key python.orm.query-inside-loop · Severity warning · Category orm
Issuing any DB read query inside a loop body (an ad-hoc find, aggregate, or repository call) produces a round-trip per iteration. Hoist the query out of the loop.
Incorrect
Section titled “Incorrect”for order in orders: customer = Customer.objects.get(id=order.customer_id) # a query per iteration notify(customer)Correct
Section titled “Correct”ids = [o.customer_id for o in orders]customers = {c.id: c for c in Customer.objects.filter(id__in=ids)} # one queryfor order in orders: notify(customers[order.customer_id])Batch the in-loop queries into a single filter(id__in=...) and move it out of the loop.