always ignore empty Q objects, if the new Q is empty, the old one will be returned.

This commit is contained in:
Stephan Jaekel 2010-05-14 14:35:27 +02:00
parent 80c2895e56
commit f657432be3
2 changed files with 8 additions and 4 deletions

View File

@ -59,6 +59,8 @@ class Q(object):
def _combine(self, other, op):
obj = Q()
if not other.query[0]:
return self
if self.query[0]:
obj.query = ['('] + copy.deepcopy(self.query) + [op] + copy.deepcopy(other.query) + [')']
else:

View File

@ -1160,17 +1160,19 @@ class QTest(unittest.TestCase):
self.assertEqual(scope, test_scope)
def test_empty_q(self):
"""Ensure that starting with an empty Q object won't hurt.
"""Ensure that empty Q objects won't hurt.
"""
q1 = Q()
q2 = Q(age__gte=18)
q3 = Q(name='test')
q3 = Q()
q4 = Q(name='test')
q5 = Q()
query = ['(', {'age__gte': 18}, '||', {'name': 'test'}, ')']
self.assertEqual((q1 | q2 | q3).query, query)
self.assertEqual((q1 | q2 | q3 | q4 | q5).query, query)
query = ['(', {'age__gte': 18}, '&&', {'name': 'test'}, ')']
self.assertEqual((q1 & q2 & q3).query, query)
self.assertEqual((q1 & q2 & q3 & q4 & q5).query, query)
if __name__ == '__main__':
unittest.main()