Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #20782 -- qs.values().aggregate() failure

In the combination of .values().aggregate() the aggregate_select_mask
didn't include the aggregates added. This resulted in bogus query.

Thanks to Trac alias debanshuk for report.
  • Loading branch information...
commit 4bd55547214ae149acadffe60536c379d51e318f 1 parent 29a09b3
Anssi Kääriäinen authored
5  django/db/models/query.py
@@ -274,9 +274,12 @@ def aggregate(self, *args, **kwargs):
274 274
 
275 275
         query = self.query.clone()
276 276
 
  277
+        aggregate_names = []
277 278
         for (alias, aggregate_expr) in kwargs.items():
278 279
             query.add_aggregate(aggregate_expr, self.model, alias,
279  
-                is_summary=True)
  280
+                                is_summary=True)
  281
+            aggregate_names.append(alias)
  282
+        query.append_aggregate_mask(aggregate_names)
280 283
 
281 284
         return query.get_aggregation(using=self.db)
282 285
 
4  django/db/models/sql/query.py
@@ -1753,6 +1753,10 @@ def set_aggregate_mask(self, names):
1753 1753
             self.aggregate_select_mask = set(names)
1754 1754
         self._aggregate_select_cache = None
1755 1755
 
  1756
+    def append_aggregate_mask(self, names):
  1757
+        if self.aggregate_select_mask is not None:
  1758
+            self.set_aggregate_mask(set(names).union(self.aggregate_select_mask))
  1759
+
1756 1760
     def set_extra_mask(self, names):
1757 1761
         """
1758 1762
         Set the mask of extra select items that will be returned by SELECT,
11  tests/aggregation/tests.py
@@ -585,3 +585,14 @@ def test_dates_with_aggregation(self):
585 585
                 "datetime.date(2008, 1, 1)"
586 586
             ]
587 587
         )
  588
+
  589
+    def test_values_aggregation(self):
  590
+        # Refs #20782
  591
+        max_rating = Book.objects.values('rating').aggregate(max_rating=Max('rating'))
  592
+        self.assertEqual(max_rating['max_rating'], 5)
  593
+        max_books_per_rating = Book.objects.values('rating').annotate(
  594
+            books_per_rating=Count('id')
  595
+        ).aggregate(Max('books_per_rating'))
  596
+        self.assertEqual(
  597
+            max_books_per_rating,
  598
+            {'books_per_rating__max': 3})

0 notes on commit 4bd5554

Please sign in to comment.
Something went wrong with that request. Please try again.