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).
Creating Composite IndexCREATE TABLE table_name ( c1 data_type PRIMARY KEY, c2 data_type, c3 data_type, c4 data_type, INDEX index_name (c2,c3,c4) ); In the above statement, the composite index consists of three columns c2, c3, and c4.
Django does create indexes automatically for some fields. For example it is stated in the documentation for Foreign Keys: A database index is automatically created on the ForeignKey. You can disable this by setting db_index to False.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
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']), ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With