Sobes.tech
Junior — Middle

How are indexes implemented in Django ORM?

sobes.tech AI

Answer from AI

In Django, indexes are implemented at the model level through the Meta inner class. To create an index, you can use the attributes index_together, unique_together, or the newer, more flexible indexes, where you can explicitly specify the index type and fields.

Example of creating an index:

from django.db import models
from django.db.models import Index

class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=50)

    class Meta:
        indexes = [
            Index(fields=['name', 'category'], name='name_category_idx'),
        ]

When migrating, Django will create the corresponding index in the database. Indexes help speed up search and sorting on specified fields.

You can also create unique indexes using unique=True on a model field or unique_together for multiple fields.