Ticket #12886: 12886.patch
File 12886.patch, 3.2 KB (added by , 14 years ago) |
---|
-
django/db/models/sql/query.py
333 333 if not self.aggregate_select: 334 334 return {} 335 335 336 # If there is a group by clause, aggregating does not add useful337 # information but retrieves only the first row. Aggregate336 # If there is a group by or limit clause, aggregating does not add 337 # useful information but retrieves only the first row. Aggregate 338 338 # over the subquery instead. 339 if self.group_by is not None :339 if self.group_by is not None or self.low_mark or self.high_mark: 340 340 from subqueries import AggregateQuery 341 341 query = AggregateQuery(self.model) 342 342 … … 390 390 obj = AggregateQuery(obj.model) 391 391 obj.add_subquery(subquery, using=using) 392 392 393 low_mark, high_mark = self.low_mark, self.high_mark 394 obj.clear_limits() 393 395 obj.add_count_column() 394 396 number = obj.get_aggregation(using=using)[None] 395 397 396 398 # Apply offset and limit constraints manually, since using LIMIT/OFFSET 397 399 # in SQL (in variants that provide them) doesn't change the COUNT 398 400 # output. 399 number = max(0, number - self.low_mark)400 if self.high_mark is not None:401 number = min(number, self.high_mark - self.low_mark)401 number = max(0, number - low_mark) 402 if high_mark is not None: 403 number = min(number, high_mark - low_mark) 402 404 403 405 return number 404 406 … … 920 922 aggregate.name, field_name, field_name)) 921 923 elif ((len(field_list) > 1) or 922 924 (field_list[0] not in [i.name for i in opts.fields]) or 923 self.group_by is None or 925 (self.group_by is None and 926 (not self.low_mark and not self.high_mark)) or 924 927 not is_summary): 925 928 # If: 926 929 # - the field descriptor has more than one part (foo__bar), or -
tests/modeltests/aggregation/tests.py
17 17 vals = Author.objects.aggregate(Avg("age")) 18 18 self.assertEqual(vals, {"age__avg": Approximate(37.4, places=1)}) 19 19 20 def test_slice_aggregate(self): 21 vals = Author.objects.all()[0:2].aggregate(Avg("age")) 22 self.assertEqual(vals, {"age__avg": Approximate(34.5, places=1)}) 23 24 def test_slice_annotate_aggregate(self): 25 vals = Author.objects.all()[0:2].annotate().aggregate(Avg("age")) 26 self.assertEqual(vals, {"age__avg": Approximate(34.5, places=1)}) 27 28 def test_join_annotate_aggregate(self): 29 vals = Book.objects.all().annotate().aggregate(Max("authors__age")) 30 self.assertEqual(len(vals), 1) 31 self.assertEqual(vals["authors__age__max"], 57) 32 20 33 def test_multiple_aggregates(self): 21 34 vals = Author.objects.aggregate(Sum("age"), Avg("age")) 22 35 self.assertEqual(vals, {"age__sum": 337, "age__avg": Approximate(37.4, places=1)})