Django Model Fields Indexing

后端 未结 2 1171
孤街浪徒
孤街浪徒 2021-01-31 15:10

I only know that indexing is helpful and it queries faster.

What is the difference between following two?

1. class Meta:
       indexes = [
           mo         


        
2条回答
  •  故里飘歌
    2021-01-31 15:37

    Example 1:

    The first example creates a single index on the last_name and first_name field.

    indexes = [
       models.Index(fields=['last_name', 'first_name',]),
    ]
    

    It will be useful if you search on the last name and first name together, or the last name by itself (because last_name is the first field in the index).

    MyModel.objects.filter(last_name=last_name, first_name=first_name)
    MyModel.objects.filter(last_name=last_name)
    

    However, it will not be useful for searching for the first_name by itself (because first_name is not the first field in the index).

    MyModel.objects.filter(first_name=first_name)  # not useful
    

    Example 2:

    The second example creates an index for the first_name field and a separate index for the last_name field.

    indexes = [
        models.Index(fields=['first_name',]),
        models.Index(fields=['last_name',]),
    ]
    

    It will be useful if you do lookups based on first name or last name in your code

    MyModel.objects.filter(first_name=search)
    MyModel.objects.filter(last_name=search)
    

提交回复
热议问题