What is the difference between Django's assertQuerysetEqual, assertNumQueries, and how do you test for query efficiency? Django के assertQuerysetEqual, assertNumQueries में क्या अंतर है, और क्वेरी दक्षता कैसे टेस्ट करें?
assertQuerysetEqual compares the contents of a queryset against an expected list of values, useful for verifying a view or method returns the correct set of objects in the correct order. assertNumQueries is a context manager that asserts exactly how many SQL queries were executed within its block, making it the standard tool for catching N+1 query regressions in tests before they reach production.
Wrapping a view call in assertNumQueries(N) fails the test if the view suddenly executes more queries than expected — for example, after someone removes a select_related() call — turning a performance regression into a hard test failure instead of a silent slowdown discovered later in production monitoring.
def test_product_list_query_count(self):
Product.objects.bulk_create([Product(name=f"P{i}") for i in range(10)])
with self.assertNumQueries(2): # 1 for products, 1 for related category prefetch
response = self.client.get(reverse('product-list'))
self.assertEqual(response.status_code, 200)assertQuerysetEqual किसी क्वेरीसेट की सामग्री की तुलना अपेक्षित वैल्यूज़ की सूची से करता है, यह सत्यापित करने के लिए उपयोगी है कि कोई व्यू या मेथड सही क्रम में सही ऑब्जेक्ट्स का सेट लौटाता है। assertNumQueries एक कॉन्टेक्स्ट मैनेजर है जो यह एसर्ट करता है कि उसके ब्लॉक के अंदर बिल्कुल कितनी SQL क्वेरीज़ चलीं।
किसी व्यू कॉल को assertNumQueries(N) में लपेटना टेस्ट को फेल कर देता है यदि व्यू अचानक अपेक्षा से अधिक क्वेरीज़ चलाए, जिससे परफॉर्मेंस रिग्रेशन एक कठोर टेस्ट फेलियर बन जाता है।
def test_product_list_query_count(self):
with self.assertNumQueries(2):
response = self.client.get(reverse('product-list'))
self.assertEqual(response.status_code, 200)Was this answer clear?