sql - Django Q&Q versus filter.filter -


while hunting bug, found out following 2 statements different things:

query 1

order.objects \   .filter(items__name__icontains="foo") \   .filter(items__name__icontains="bar") \   .distinct() 

query 2

order.objects \   .filter(     q(items__name__icontains="foo") &     q(items__name__icontains="bar")   ) \   .distinct() 

the result follows:

  • query 1 include orders have items either contain "foo" or "bar". example 1 item's name "foo" while item's name "bar".
  • query 2 includes orders have at least 1 item contains all keywords, example item name of "foo bar".

looking @ queries, can see filter() method adds inner join query while other doesn't.

i can see reasoning behind this, wonder if that's intended behavior.

the difference first query has 2 filter() calls, , second query has one.

the first query tries find object related item containing 'foo' , related item containing 'bar'. second query tries find item single related item contains both 'foo' , 'bar'

the fact 1 uses q() objects not significant - change first query to:

order.object.filter(     q(items__name__icontains="foo" ).filter(     q(items__name__icontains="bar") ) 

however q() required in second query 2m since invalid python repeat keyword argument in .filter(items__name__icontains="foo", items__name__icontains="bar")

see docs on spanning multi-values relationships more info.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -