Django Model Field Indexing

I only know that indexing is useful, and it queries faster.

What is the difference between the following two?

1. class Meta: indexes = [ models.Index(fields=['last_name', 'first_name',]), models.Index(fields=['-date_of_birth',]), ] 2. class Meta: indexes = [ models.Index(fields=['first_name',]), models.Index(fields=['last_name',]), models.Index(fields=['-date_of_birth',]), ] 
+7
django indexing django-models
source share
2 answers

The first 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',]), ] 

This will be useful if you search by first or last name in your code.

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

The second example creates a single index in the last_name and first_name fields.

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

This will be useful if you look for the last name and first name together or the last name yourself (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, this will not be useful for finding first_name alone (since first_name not the first field in the index).

 MyModel.objects.filter(first_name=first_name) 
+4
source share

Django Model Index was introduced in Django 1.11

What is Model.indexes:

By default, indexes are created in ascending order for each column. To define an index in descending order for a column, add a hyphen in front of the field name.

At your request, models.Index(fields=['last_name', 'first_name','-date_of_birth',]), will create SQL with (last_name, first_name, date_of_birth DESC).

Let's get to your question,

you set the difference between the two queries,

both will take models.Index(fields=['-date_of_birth',]),

because at least one of them will override the assigned variables. from your question the smallest dateofbirth value, so it will be redefined over two lines.

, since the preferred document method, because the index field must be on the same list .. so django will prepare SQL indexing from the list of fields ...

 models.Index(fields=['last_name', 'first_name', '-date_of_birth']), 
+1
source share

All Articles