Skip to content

Commit

Permalink
Fixed #28863 -- Fixed filter on annotation that contains Q.
Browse files Browse the repository at this point in the history
  • Loading branch information
sir-sigurd authored and timgraham committed Dec 2, 2017
1 parent c3e0adc commit cf12257
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
8 changes: 7 additions & 1 deletion django/db/models/sql/where.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class WhereNode(tree.Node):
contains_aggregate attribute.
"""
default = AND
resolved = False

def split_having(self, negated=False):
"""
Expand Down Expand Up @@ -108,7 +109,7 @@ def as_sql(self, compiler, connection):
# around the inner SQL in the negated case, even if the
# inner SQL contains just a single expression.
sql_string = 'NOT (%s)' % sql_string
elif len(result) > 1:
elif len(result) > 1 or self.resolved:
sql_string = '(%s)' % sql_string
return sql_string, result_params

Expand Down Expand Up @@ -181,6 +182,11 @@ def contains_over_clause(self):
def is_summary(self):
return any(child.is_summary for child in self.children)

def resolve_expression(self, *args, **kwargs):
clone = self.clone()
clone.resolved = True
return clone


class NothingNode:
"""A node that matches nothing."""
Expand Down
9 changes: 9 additions & 0 deletions tests/expressions/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ def test_annotate_values_filter(self):
],
)

@unittest.skipIf(connection.vendor == 'oracle', "Oracle doesn't support using boolean type in SELECT")
def test_filtering_on_annotate_that_uses_q(self):
self.assertEqual(
Company.objects.annotate(
num_employees_check=ExpressionWrapper(Q(num_employees__gt=3), output_field=models.BooleanField())
).filter(num_employees_check=True).count(),
2,
)

def test_filter_inter_attribute(self):
# We can filter on attribute relationships on same model obj, e.g.
# find companies where the number of employees is greater
Expand Down

0 comments on commit cf12257

Please sign in to comment.