Reputation: 357
I have a question about optimizing gets and filters in Django. I'd assume my hunch is correct on this, but I can't find any confirmation.
When applying multiple constraints on a get()
or filter()
query, and one or more of those constraints is on a foreign key or m2m object, does the order of the constraints matter for efficiency? Example statements, to find children whose names are Bob and whose father's name is also Bob: It would be efficient if Django first checked each Child to see if its name is "Bob" and, if not, it wouldn't bother checking the father's name. I could make slightly different queries as such: Child.objects.filter(name="Bob", father__name="Bob")
and Child.objects.filter(father__name="Bob",name="Bob")
.
So, my question is, does Django act in an efficient manner, only following foreign keys if the local values already match? Basically, here are the three possibilities I can think of:
Thanks!
Upvotes: 1
Views: 767
Reputation: 2314
The kind of performance optimization you suggest is a task for the database engine. Django will send off a query and the database will make the best it can out of it. The following seems to have some details on what MySQL does with the query: https://www.informit.com/articles/article.aspx?p=377652&seqNum=2
If you have a sizable amount of data, the best way to find out if there's a difference is to measure it. If you don't have enough data to do meaningful measurements, then the result doesn't matter.
Upvotes: 1