index_together的顺序在Django模型中是否重要?

时间:2022-10-16 19:22:02

When defining a model with an index_together Meta property, does the order of the columns matter?

在使用index_together Meta属性定义模型时,列的顺序是否重要?

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

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?

我只是问,因为我注意到在查看表的结构时,键中的每一列都有一个“key in key”属性。 MySQL / PostgreSQL是否希望按顺序查询列?

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

除此之外,将列一起索引与单独索引之间是否存在很大差异?

1 个解决方案

#1


9  

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.

index_together的顺序解释了创建索引的“路径”。您可以从左向右查询以从索引中获利。

So with your first index_together:

所以你的第一个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.

但是,如果按地址过滤,然后按名称或地址过滤,则不能使用favorite_color索引。

#1


9  

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.

index_together的顺序解释了创建索引的“路径”。您可以从左向右查询以从索引中获利。

So with your first index_together:

所以你的第一个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.

但是,如果按地址过滤,然后按名称或地址过滤,则不能使用favorite_color索引。