İçeriğe geç

Döngü İçinde Sorgu (ARCH2064)

Anahtar python.orm.query-inside-loop · Önem warning · Kategori orm

Döngü gövdesinde herhangi bir DB okuma sorgusu (ad-hoc find, agregat, repository çağrısı) çalıştırmak, iterasyon başına round-trip üretir. Sorguyu döngü dışına taşıyın.

for order in orders:
customer = Customer.objects.get(id=order.customer_id) # her turda sorgu
notify(customer)
ids = [o.customer_id for o in orders]
customers = {c.id: c for c in Customer.objects.filter(id__in=ids)} # tek sorgu
for order in orders:
notify(customers[order.customer_id])

Döngü içindeki sorguları tek bir filter(id__in=...) ile toplayıp döngü dışına çıkarın.