Reputation: 41665
Does order
of filter
matter when you query in django?
MyModel.objects.filter(exp1).filter(exp2)
vs
MyModel.objects.filter(exp2).filter(exp1)
Are they same?
Upvotes: 6
Views: 2558
Reputation: 36511
If you are just doing two simple filter
operations, then you're correct that order doesn't matter, but be careful. There are examples of when the order of your queryset methods do matter:
Rather than thinking of filter
as being fundamentally commutative, you're probably safer thinking of each queryset methods as being generally iterative upon the whatever preceded them. Multiple filters are not always simple SQL AND's. Take this for example (although it's still commutative in this case).
Upvotes: 3
Reputation: 11038
filter(exp1).filter(exp2) filters according to exp1 and then subfilter exp2 (restricting furthermore the result queryset, with results that are ALSO in exp2)
so actually your answer is yes, they are the same, since this acts like an ordinary AND query
Upvotes: 0