Create composite index from a Django model

Starting from Django-1.11 use Meta.indexes option https://docs.djangoproject.com/en/1.11/ref/models/indexes/:

from django.db import models

class PopulationData(models.Model):
    slot = models.IntegerField(db_index=True)
    sample = models.IntegerField()
    value = models.FloatField()

    class Meta:
        unique_together = (('slot', 'sample'),)
        indexes = [
            models.Index(fields=['slot', 'sample']),
        ]

Since a unique constraint also creates an index, it would be counterproductive to create both.

for example, from the postgres docs:

There's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.

Credit to Mark Byers for the doc link

If for some reason you still want to create a multi-column index, you can do so via index_together:

class PopulationData(models.Model):
    ...

    class Meta:
        index_together = [['slot', 'sample']]

I think that's not currently implemented in the django ORM.

If you use a migration tool (like south) that might be a good place to add that sql statement or if you preffer to avoid raw sql you could use sqlalchemy (core) but this case sounds simple enough to just go with sql.


Starting from django-1.5 you can make compound index using index_together meta option: https://docs.djangoproject.com/en/dev/ref/models/options/#index-together