How to make a filter in a model (Django/ORM) respecting the place of the fields in the query?

Viewed 30

I have a model Student with this fields: id, first_name, last_name. I added a compose index with first_name and last_name.

The problem is when i filter. I use Student.objects.filter(last_name='Caicedo', first_name='Pedro') but the internal ORM select is:

SELECT `students`.`id`, `students`.`first_name`, `students`.`last_name` 
FROM `students` 
WHERE (`students`.`first_name` = 'Pedro' AND `students`.`last_name` = 'Caicedo'); args=('Pedro', 'Caicedo');

It does not respect the order, and I need to respect it by optimizing the query.

1 Answers

Investigating this can be solved using Q functions. Example:

from django.db.models import Q

Student.objects.filter(Q(last_name='Caicedo'), Q(first_name= 'Pedro'))

Now my query is correct and I can take advantage of the index created in the table.

Related