Does the order of index_together matter in the Django model?

When defining a model using the meta property, index_together does column order matter?

In other words, is there a difference between

Class myModel(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) favorite_color = models.CharField(max_length=20) class Meta: index_together = ('name', 'address', 'favorite_color') 

against

 Class myModel(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) favorite_color = models.CharField(max_length=20) class Meta: index_together = ('favorite_color', 'name', 'address') 

I just ask, because I noticed, looking at the structure of the table, each column in the key has the property "index in key". MySQL / PostgreSQL expects columns to be queried in this order?

As an aside, is there a big difference between indexing columns together and separately?

+7
sql django mysql postgresql
source share
1 answer

The order index_together explains the "path" that the index creates. You can query from left to right to profit from the index.

So, with your first index_together :

  index_together = ('name', 'address', 'favorite_color') 

if your first name filter is using an index. If the first is name and the second is address , the index is also used.

But if you filter by address , and then name or address , favorite_color , the index cannot be used.

+8
source share

All Articles