How do you use only(), defer(), and values()/values_list() to optimize queries? क्वेरीज़ को ऑप्टिमाइज़ करने के लिए only(), defer() और values()/values_list() का उपयोग कैसे करें?
By default, a queryset fetches every field of a model, which wastes bandwidth and memory when only a few fields are actually needed — especially with large text or binary fields. only('field1', 'field2') restricts the SELECT to just the named fields (plus the primary key), while defer('field1') does the opposite, fetching everything except the named fields, deferred until accessed.
values() and values_list() go further by skipping model instantiation entirely, returning dictionaries or tuples instead of full model objects — much cheaper when you only need raw data for a report, export, or API response and don't need model methods or related-object traversal. Accessing a deferred field triggers an additional query per instance, so defer()/only() should be used carefully alongside select_related() when related fields are also needed.
Product.objects.only('name', 'price')
Product.objects.defer('description')
Product.objects.values('name', 'price')
Product.objects.values_list('name', flat=True)डिफ़ॉल्ट रूप से, एक क्वेरीसेट मॉडल की हर फील्ड फेच करता है, जो बैंडविड्थ और मेमोरी बर्बाद करता है जब वास्तव में केवल कुछ फील्ड्स की ज़रूरत हो। only('field1', 'field2') SELECT को केवल नामित फील्ड्स तक सीमित करता है।
values() और values_list() मॉडल इंस्टैंशिएशन को पूरी तरह छोड़कर आगे जाते हैं, पूर्ण मॉडल ऑब्जेक्ट्स के बजाय डिक्शनरी या टपल रिटर्न करते हैं।
Product.objects.only('name', 'price')
Product.objects.values('name', 'price')
Product.objects.values_list('name', flat=True)Was this answer clear?