Create composite index from a Django model

I have the following model:

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'),)

And I would like to create also a compound index on the column pair that have the UNIQUE constraint, like so:

CREATE INDEX my_compound_index ON myapp_populationdata (slot, sample);

Right now I have a separate code connected to the post_syncdb signal that issues the previous SQL statement. Is there any way to indicate it from the model specification? (Note: I'm using the 1.3 branch).

Answers


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


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']),
        ]

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.


Need Your Help

What does double bars (||) mean in SQL?

mysql sql

I'm trying to understand the following query:

Socket.io error hooking into express.js

javascript node.js express socket.io

I'm trying to hook socket.io and express.js together: