Fixed #32126 -- Fixed grouping by Case() annotation without cases.

Co-authored-by: Simon Charette <charettes@users.noreply.github.com>
This commit is contained in:
Hannes Ljungberg 2020-10-19 22:36:24 +02:00 committed by Mariusz Felisiak
parent 4343430e9c
commit 0e7a45fca0
2 changed files with 30 additions and 0 deletions

View File

@ -1068,6 +1068,11 @@ class Case(Expression):
sql = connection.ops.unification_cast_sql(self.output_field) % sql
return sql, sql_params
def get_group_by_cols(self, alias=None):
if not self.cases:
return self.default.get_group_by_cols(alias)
return super().get_group_by_cols(alias)
class Subquery(Expression):
"""

View File

@ -1148,6 +1148,31 @@ class CaseExpressionTests(TestCase):
lambda x: x[1:]
)
def test_aggregation_empty_cases(self):
tests = [
# Empty cases and default.
(Case(output_field=IntegerField()), None),
# Empty cases and a constant default.
(Case(default=Value('empty')), 'empty'),
# Empty cases and column in the default.
(Case(default=F('url')), ''),
]
for case, value in tests:
with self.subTest(case=case):
self.assertQuerysetEqual(
CaseTestModel.objects.values('string').annotate(
case=case,
integer_sum=Sum('integer'),
).order_by('string'),
[
('1', value, 1),
('2', value, 4),
('3', value, 9),
('4', value, 4),
],
transform=itemgetter('string', 'case', 'integer_sum'),
)
class CaseDocumentationExamples(TestCase):
@classmethod