[Django]-Django Model Fields Indexing

151👍

Example 1:

The first example creates a single index on the last_name and first_name field.

indexes = [
   models.Index(fields=['last_name', 'first_name',]),
]

It will be useful if you search on the last name and first name together, or the last name by itself (because last_name is the first field in the index).

MyModel.objects.filter(last_name=last_name, first_name=first_name)
MyModel.objects.filter(last_name=last_name)

However, it will not be useful for searching for the first_name by itself (because first_name is not the first field in the index).

MyModel.objects.filter(first_name=first_name)  # not useful

Example 2:

The second example creates an index for the first_name field and a separate index for the last_name field.

indexes = [
    models.Index(fields=['first_name',]),
    models.Index(fields=['last_name',]),
]

It will be useful if you do lookups based on first name or last name in your code

MyModel.objects.filter(first_name=search)
MyModel.objects.filter(last_name=search)

6👍

Django Model Index was introduced in Django 1.11

what is Model.indexes:

By default, indexes are created with an ascending order for each column. To define an index with a descending order for a column, add a hyphen before the field’s name.

For your query,
models.Index(fields=['last_name', 'first_name','-date_of_birth',]), would create SQL with (last_name, first_name, date_of_birth DESC).

Lets move to your question,

you asked difference between 2 queries,

both will take models.Index(fields=['-date_of_birth',]),

because least one will override the assigned variables. from your question least is dateofbirth so it will override above two lines.

so as per documentation preferable method is,
because indexing field should be in single list.. so django will prepare SQL indexing from list of fields…

models.Index(fields=['last_name', 'first_name', '-date_of_birth']),

1👍

Django Model Fields Indexing Example for Book model, It will be helpful to implement:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    publication_year = models.IntegerField()

    class Meta:
        indexes = [
            models.Index(fields=['author', 'publication_year'], name='author_pub_year_idx'),
            models.Index(fields=['title'], name='title_idx'),
        ]

Leave a comment