I have a interesting Django problem.
Consider the following:
Model.objects.filter(Q(id=\'test1\') and Q(id=\'test2\'))
this returns the
If you want Django ORM to return test1 and test2, you should use :
Model.objects.filter(Q(id='test1') | Q(id='test2'))
Model.objects.filter(Q(id='test1') & Q(id='test2'))
means return model objects whose id is test1 while its is test2 at the same time. Of course, django will return an empty QuerySet.
and is a boolean operator in Python. For operation x and y
the result is if x is false, then x, else y
. Thus Q(id='test1') and Q(id='test2')
equals Q(id='test1')
, it is not what you want.
&/| is the the bitwise and/or operator.
BTW, there's no way to override the boolean operator, but you can override &/|
operators in your class by define a method named __and__
/ __or__
.
below is the source code of the django Q object[github]:
class Q(tree.Node):
"""
Encapsulates filters as objects that can then be combined logically (using
& and |).
"""
# Connection types
AND = 'AND'
OR = 'OR'
default = AND
def __or__(self, other):
return self._combine(other, self.OR)
def __and__(self, other):
return self._combine(other, self.AND)
...