Skip to content

Commit aeb8996

Browse files
committed
Fixed #31659 -- Made ExpressionWrapper preserve output_field for combined expressions.
Regression in df32fd4. Thanks Simon Charette for the review.
1 parent 5776a16 commit aeb8996

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

django/db/models/expressions.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -857,6 +857,9 @@ class ExpressionWrapper(Expression):
857857

858858
def __init__(self, expression, output_field):
859859
super().__init__(output_field=output_field)
860+
if getattr(expression, '_output_field_or_none', True) is None:
861+
expression = expression.copy()
862+
expression.output_field = output_field
860863
self.expression = expression
861864

862865
def set_source_expressions(self, exprs):

tests/annotations/tests.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,14 @@ def test_annotate_with_aggregation(self):
170170
self.assertEqual(book.is_book, 1)
171171
self.assertEqual(book.rating_count, 1)
172172

173+
def test_combined_expression_annotation_with_aggregation(self):
174+
book = Book.objects.annotate(
175+
combined=ExpressionWrapper(Value(3) * Value(4), output_field=IntegerField()),
176+
rating_count=Count('rating'),
177+
).first()
178+
self.assertEqual(book.combined, 12)
179+
self.assertEqual(book.rating_count, 1)
180+
173181
def test_aggregate_over_annotation(self):
174182
agg = Author.objects.annotate(other_age=F('age')).aggregate(otherage_sum=Sum('other_age'))
175183
other_agg = Author.objects.aggregate(age_sum=Sum('age'))

tests/expressions/tests.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1837,4 +1837,6 @@ def test_empty_group_by(self):
18371837

18381838
def test_non_empty_group_by(self):
18391839
expr = ExpressionWrapper(Lower(Value('f')), output_field=IntegerField())
1840-
self.assertEqual(expr.get_group_by_cols(alias=None), [expr.expression])
1840+
group_by_cols = expr.get_group_by_cols(alias=None)
1841+
self.assertEqual(group_by_cols, [expr.expression])
1842+
self.assertEqual(group_by_cols[0].output_field, expr.output_field)

0 commit comments

Comments
 (0)