Django Model Fields Indexing

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)