Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create composite index from a Django model

Tags:

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).

like image 473
C2H5OH Avatar asked Apr 07 '13 18:04

C2H5OH


People also ask

How do I create a composite column index?

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.

Does Django create indexes?

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.

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.


2 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

like image 136
Eugene Prikazchikov Avatar answered Sep 22 '22 12:09

Eugene Prikazchikov


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']),         ] 
like image 20
Artem Likhvar Avatar answered Sep 22 '22 12:09

Artem Likhvar