From 4e6f0024f19f74be2fe4d9ec637b87e82054ebd6 Mon Sep 17 00:00:00 2001 From: Étienne Beaulé Date: Tue, 4 Jun 2019 04:01:16 -0300 Subject: [2.2.x] Fixed #30542 -- Fixed crash of numerical aggregations with filter. Filters in annotations crashed when used with numerical-type aggregations (i.e. Avg, StdDev, and Variance). This was caused as the source expressions no not necessarily have an output_field (such as the filter field), which lead to an AttributeError: 'WhereNode' object has no attribute output_field. Thanks to Chuan-Zheng Lee for the report. Regression in c690afb873cac8035a3cb3be7c597a5ff0e4b261 and two following commits. Backport of 4b6dfe16226a81fea464ac5f77942f4d6ba266e8 from master. --- tests/aggregation/test_filter_argument.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'tests/aggregation') diff --git a/tests/aggregation/test_filter_argument.py b/tests/aggregation/test_filter_argument.py index 63dee59464..9d6c0a52af 100644 --- a/tests/aggregation/test_filter_argument.py +++ b/tests/aggregation/test_filter_argument.py @@ -1,8 +1,11 @@ import datetime from decimal import Decimal -from django.db.models import Case, Count, F, Q, Sum, When +from django.db.models import ( + Avg, Case, Count, F, Q, StdDev, Sum, Variance, When, +) from django.test import TestCase +from django.test.utils import Approximate from .models import Author, Book, Publisher @@ -40,6 +43,16 @@ class FilteredAggregateTests(TestCase): agg = Sum('age', filter=Q(name__startswith='test')) self.assertEqual(Author.objects.aggregate(age=agg)['age'], 200) + def test_filtered_numerical_aggregates(self): + for aggregate, expected_result in ( + (Avg, Approximate(66.7, 1)), + (StdDev, Approximate(24.9, 1)), + (Variance, Approximate(622.2, 1)), + ): + with self.subTest(aggregate=aggregate.__name__): + agg = aggregate('age', filter=Q(name__startswith='test')) + self.assertEqual(Author.objects.aggregate(age=agg)['age'], expected_result) + def test_double_filtered_aggregates(self): agg = Sum('age', filter=Q(Q(name='test2') & ~Q(name='test'))) self.assertEqual(Author.objects.aggregate(age=agg)['age'], 60) -- cgit v1.3