Bug fix: wrong parentheses when building queries using Q objects

This commit is contained in:
Itai Shirav 2018-10-13 19:49:12 +03:00
parent f2a731711d
commit 658c7b42ee
3 changed files with 7 additions and 2 deletions

View File

@ -4,6 +4,7 @@ Change Log
Unreleased Unreleased
---------- ----------
- Bug fix: `QuerySet.count()` ignores slicing - Bug fix: `QuerySet.count()` ignores slicing
- Bug fix: wrong parentheses when building queries using Q objects
v1.0.2 v1.0.2
---------- ----------

View File

@ -188,7 +188,7 @@ class Q(object):
q = Q() q = Q()
q._l_child = l_child q._l_child = l_child
q._r_child = r_child q._r_child = r_child
q._mode = mode q._mode = mode # AND/OR
return q return q
def _build_fov(self, key, value): def _build_fov(self, key, value):
@ -203,7 +203,7 @@ class Q(object):
sql = ' {} '.format(self._mode).join(fov.to_sql(model_cls) for fov in self._fovs) sql = ' {} '.format(self._mode).join(fov.to_sql(model_cls) for fov in self._fovs)
else: else:
if self._l_child and self._r_child: if self._l_child and self._r_child:
sql = '({}) {} ({})'.format( sql = '({} {} {})'.format(
self._l_child.to_sql(model_cls), self._mode, self._r_child.to_sql(model_cls)) self._l_child.to_sql(model_cls), self._mode, self._r_child.to_sql(model_cls))
else: else:
return '1' return '1'

View File

@ -75,6 +75,10 @@ class QuerySetTestCase(TestCaseWithData):
self._test_qs(qs.filter((Q(first_name__in=['Warren', 'Whilemina', 'Whitney']) & Q(height__gte=1.7) | self._test_qs(qs.filter((Q(first_name__in=['Warren', 'Whilemina', 'Whitney']) & Q(height__gte=1.7) |
(Q(first_name__in=['Victoria', 'Victor', 'Venus']) & Q(height__lt=1.7)))), 4) (Q(first_name__in=['Victoria', 'Victor', 'Venus']) & Q(height__lt=1.7)))), 4)
self._test_qs(qs.filter(Q(first_name='Elton') & ~Q(last_name='Smith')), 1) self._test_qs(qs.filter(Q(first_name='Elton') & ~Q(last_name='Smith')), 1)
# Check operator precendence
self._test_qs(qs.filter(first_name='Cassady').filter(Q(last_name='Knapp') | Q(last_name='Rogers') | Q(last_name='Gregory')), 2)
self._test_qs(qs.filter(Q(first_name='Cassady') & Q(last_name='Knapp') | Q(first_name='Beatrice') & Q(last_name='Gregory')), 2)
self._test_qs(qs.filter(Q(first_name='Courtney') | Q(first_name='Cassady') & Q(last_name='Knapp')), 3)
def test_filter_unicode_string(self): def test_filter_unicode_string(self):
self.database.insert([ self.database.insert([