How does Django's QuerySet laziness work, and when does a queryset actually hit the database? Django का QuerySet लेज़ीनेस कैसे काम करता है, और QuerySet वास्तव में डेटाबेस को कब हिट करता है?
A Django QuerySet is lazy: creating or chaining it (filter(), exclude(), order_by()) only builds up a SQL query description without executing anything against the database. This lets querysets be composed and passed around cheaply, and lets Django combine multiple chained filters into a single efficient query rather than running one per method call.
The query only actually executes when the queryset is evaluated — iterating over it, calling len(), slicing with a step, calling list(), printing/repr in a shell, or calling a method that must return a concrete value like .count(), .exists(), .first(), or .get(). Understanding this distinction is essential for spotting accidental double-evaluation.
qs = Product.objects.filter(price__gt=100) # no query yet
qs = qs.order_by('name') # still no query
list(qs) # query executes nowDjango का QuerySet लेज़ी होता है: इसे बनाना या चेन करना (filter(), exclude()) केवल एक SQL क्वेरी विवरण बनाता है बिना डेटाबेस के विरुद्ध कुछ भी एक्ज़ीक्यूट किए। यह क्वेरीसेट्स को सस्ते में कंपोज़ करने देता है।
क्वेरी तब ही वास्तव में चलती है जब क्वेरीसेट का मूल्यांकन किया जाता है — इस पर इटरेट करना, len() कॉल करना, list() कॉल करना, या .count(), .exists(), .first() जैसी मेथड कॉल करना।
qs = Product.objects.filter(price__gt=100)
qs = qs.order_by('name')
list(qs)Was this answer clear?