From 0e7a45fca09623e7bad9408a838e522b3cca8d65 Mon Sep 17 00:00:00 2001 From: Hannes Ljungberg Date: Mon, 19 Oct 2020 22:36:24 +0200 Subject: [PATCH] Fixed #32126 -- Fixed grouping by Case() annotation without cases. Co-authored-by: Simon Charette --- django/db/models/expressions.py | 5 +++++ tests/expressions_case/tests.py | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index 43b8920d951..13918467ee3 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -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): """ diff --git a/tests/expressions_case/tests.py b/tests/expressions_case/tests.py index 2a101eeee16..54c53ef4def 100644 --- a/tests/expressions_case/tests.py +++ b/tests/expressions_case/tests.py @@ -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