I have Query which shows different results when i use and or &
criteria1 = Q(id__gte=802, id__lte=1000)
criteria2 = Q(country_id__contains='UK')
I always have been using :
q = Mymodel.objects.filter(criteria1 & criteria2)
But in this particular case when i use & it always outputs a single row . (I also checked print q.query(), query comes out to be fine)
However, when i use and instead of &. Query gives correct output
q = Mymodel.objects.filter(criteria1 and criteria2)
what actually is happening under the hood ?
Use vs Usage It is not correct to interchange them since they are different in their meanings. The word use is used in the sense of 'employ'. On the other hand, the word usage is used in the sense of 'practice' or 'convention' or 'the act of using something'. This is the main difference between the two words.
We use by to show how someone does something but we use with to show the tool or object used to do something: I made this cake by hand. I made this cake with the oven.
The correct one is criteria1 & criteria2
. criteria1 and criteria2
uses standard Python boolean logic and will be evaluated into criteria2
, while criteria1 & criteria2
uses overloaded __and__
method and constructs correct compound Q
object:
In [1]: from django.db.models import Q
In [2]: criteria1 = Q(id__gte=802, id__lte=1000)
In [3]: criteria2 = Q(country_id__contains='UK')
In [4]: criteria1 & criteria2
Out[4]: <Q: (AND: ('id__gte', 802), ('id__lte', 1000), ('country_id__contains', 'UK'))>
In [5]: criteria1 and criteria2
Out[5]: <Q: (AND: ('country_id__contains', 'UK'))>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With