views:

1557

answers:

3

Given the following model, I want to index the fields (sequence,stock)

class QuoteModel(models.Model):  
    quotedate =  models.DateField()  
    high = models.FloatField() #(9,2) DEFAULT NULL,  
    low  = models.FloatField() #(9,2) DEFAULT NULL,  
    close  = models.FloatField() #(9,2) DEFAULT NULL,  
    closeadj  = models.FloatField() #(9,2) DEFAULT NULL,  
    volume  = models.IntegerField() #(9,2) DEFAULT NULL,  
    stock  = models.IntegerField(db_index=True) #(9,2) DEFAULT NULL,  
    open  = models.FloatField() #(9,2) DEFAULT NULL,  
    sequence = models.IntegerField() #(9,2) DEFAULT NULL,

This index should be non-unique - in mysql it should be something like:

create index ndx_1 on model_quotemodel(sequence,stock);

The only Django workaround I know of is creating an "sql" file that will be executed by django upon table creation. So, I created a "stockmodel.sql" containing the following query (same as above:)

create index ndx_1 on model_quotemodel(sequence,stock);

Is there any "cleaner" way of doing it?

+1  A: 

Using db_index=True should create a non-unique index, unless the field also has unique=True. Are you sure it's creating a unique index?

Dominic Rodger
Yes, I do have an index at the "stock" field. But I need *another* index on fields (sequence, stock) - a multiple column index, non-unique.
jbastos
+3  A: 

No, this isn't currently implemented in Django. However, there's a ticket for composite primary keys and a Django fork maintained by ticket's assignee that implements it. So, your way of doing this is best in terms of built-in tools. You may also want to try using some DB migration system like south if your project is quite large.

excieve
A: 

unique_together might be what you are looking for. Just put it in your Meta class inside your model.

craesh