Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · Django Performance & Optimization
Interview question

How do you add database indexes in Django models, and when should you use them? Django मॉडल्स में डेटाबेस इंडेक्स कैसे जोड़ें, और इनका उपयोग कब करना चाहिए?

Answer

A database index is a separate data structure that lets the database look up rows matching a condition without scanning the entire table, dramatically speeding up queries that filter, order, or join on that column — at the cost of extra storage and slightly slower writes, since indexes must be updated on every insert/update.

In Django, an index is added by setting db_index=True on a field or, preferably for multi-column and more control, adding entries to a model's Meta.indexes list using models.Index. Indexes are most valuable on columns frequently used in filter(), order_by(), or as foreign keys (which Django indexes automatically); indexing every column indiscriminately hurts write performance without meaningful read benefit.

class Order(models.Model):
    status = models.CharField(max_length=20, db_index=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    created_at = models.DateTimeField()

    class Meta:
        indexes = [
            models.Index(fields=['status', 'created_at']),
        ]

डेटाबेस इंडेक्स एक अलग डेटा संरचना है जो डेटाबेस को पूरी टेबल स्कैन किए बिना किसी शर्त से मेल खाने वाली पंक्तियों को खोजने देता है, जिससे उस कॉलम पर फ़िल्टर, ऑर्डर या जॉइन करने वाली क्वेरीज़ काफी तेज़ हो जाती हैं।

Django में, इंडेक्स किसी फील्ड पर db_index=True सेट करके, या मल्टी-कॉलम और अधिक नियंत्रण के लिए मॉडल के Meta.indexes सूची में models.Index का उपयोग करके जोड़ा जाता है।

class Order(models.Model):
    status = models.CharField(max_length=20, db_index=True)
    class Meta:
        indexes = [models.Index(fields=['status', 'created_at'])]

Was this answer clear?