How do you use Django's database query optimization tools: explain(), Prefetch objects, and annotate()? Django के डेटाबेस क्वेरी ऑप्टिमाइज़ेशन टूल्स का उपयोग कैसे करें: explain(), Prefetch ऑब्जेक्ट्स और annotate()?
queryset.explain() returns the database's query execution plan (showing whether an index is actually used, join strategy, and estimated row counts), the primary diagnostic tool for understanding why a query is slow instead of guessing. annotate() lets aggregate calculations (counts, sums, averages) be computed in the database rather than pulled into Python and looped over, which is both faster and uses far less memory for large datasets.
A Prefetch object gives fine-grained control over prefetch_related() beyond a plain field name — it can filter, order, or limit the related queryset being prefetched, and store the result under a custom attribute name, letting you prefetch only the relevant subset of related objects instead of all of them.
from django.db.models import Prefetch, Count
Order.objects.filter(status='pending').explain()
Category.objects.annotate(product_count=Count('products'))
Customer.objects.prefetch_related(
Prefetch('orders', queryset=Order.objects.filter(created_at__gte=last_month))
)queryset.explain() डेटाबेस की क्वेरी एक्ज़ीक्यूशन प्लान लौटाता है, यह समझने का प्राथमिक डायग्नोस्टिक टूल कि कोई क्वेरी धीमी क्यों है। annotate() एग्रीगेट गणनाओं को Python में लूप करने के बजाय डेटाबेस में करने देता है।
एक Prefetch ऑब्जेक्ट सादे फील्ड नाम से आगे prefetch_related() पर सूक्ष्म नियंत्रण देता है।
Order.objects.filter(status='pending').explain()
Category.objects.annotate(product_count=Count('products'))
Customer.objects.prefetch_related(
Prefetch('orders', queryset=Order.objects.filter(created_at__gte=last_month))
)Was this answer clear?