Adding indexes to model fields in Django with migrations

Nima picture Nima · Sep 29, 2014 · Viewed 11.5k times · Source

I am trying to add indexes on model fields using Field.db_index for an app that has migrations. Looking at Django's documentation all I need to do is to set db_index=True:

class Person(models.Model):
    first_name = models.CharField()
    last_name = models.CharField(db_index=True)

and then I first tried the new Django's Migration:

./manage.py makemigrations app-name

but Migration does not seem to notice the change and does not add the sql command for creating an index. So I tried django-admin.py as explained here:

django-admin.py sqlindexes app-name

But that does not print the sql command either and it exits with the following error:

CommandError: App 'app-name' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations.

Answer

ilse2005 picture ilse2005 · Mar 20, 2019

This problem still exists in django2.1. I solved it by using the indexes Meta option. This is a bit cleaner than the index_together solution.

class Person(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()

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