Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of index_together matter in a Django model?

When defining a model with an index_together Meta property, does the order of the columns 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')

vs

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 only ask because I've noticed when looking at the structure of a table, each column in the key has an "index in key" property. Does MySQL/PostgreSQL expect the columns to be queried in that order?

Just as an aside, is there a great deal of difference between indexing the columns together vs separately?

like image 249
Luke Sapan Avatar asked Feb 13 '14 12:02

Luke Sapan


People also ask

What is ordering in Django model?

Django order by lets you specify how your query results should be ordered. Here's an example where we will order by the author's name: class Author(models.Model): name = models.CharField() Author.objects.order_by("name")

What is ordering in Meta class?

class Meta: verbose_name = "stu" # add verbose_name here. 4. ordering. Ordering is basically used to change the order of your model fields.

What is index in Django model?

Django Model Index was introduced in Django 1.11. what is Model. indexes: By default, indexes are created with an ascending order for each column. To define an index with a descending order for a column, add a hyphen before the field's name.

What is Unique_together in Django?

What is Unique_together in Django? Django unique_together is used to make two or more model fields to be unique. class MyModel(models.Model): field1 = models.CharField(max_length=50) field2 = models.CharField(max_length=50) field3 = models.CharField(max_length=50) class Meta: unique_together = ('field1', 'field2',)


1 Answers

The order of index_together explains the "path" the index is created. You can query from left to the right to profit from the index.

So with your first index_together:

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

if your first filter is name the index is used. If the first is name and the second is address the index is used, too.

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

like image 78
tjati Avatar answered Sep 20 '22 08:09

tjati