Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django, order matters when applying multiple query filters?

Tags:

django

filter

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?

like image 458
eugene Avatar asked Oct 21 '22 23:10

eugene


1 Answers

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:

  • https://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses
  • https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

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).

like image 66
acjay Avatar answered Oct 27 '22 10:10

acjay