Skip to content

Commit bebbbb7

Browse files
nmfmakaariai
authored andcommitted
Fixed django#18056 - Cleared aggregations on DateQuery.add_date_select
Cleared aggregations on add_date_select method so only distinct dates are returned when dealing with a QuerySet that contained aggregations. That would cause the query set to return repeated dates because it would look for distinct (date kind, aggregation) pairs.
1 parent 35ddeee commit bebbbb7

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

django/db/models/sql/subqueries.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from django.db.models.sql.datastructures import Date
99
from django.db.models.sql.query import Query
1010
from django.db.models.sql.where import AND, Constraint
11+
from django.utils.datastructures import SortedDict
1112
from django.utils.functional import Promise
1213
from django.utils.encoding import force_unicode
1314

@@ -205,6 +206,7 @@ def add_date_select(self, field_name, lookup_type, order='ASC'):
205206
self.select = [select]
206207
self.select_fields = [None]
207208
self.select_related = False # See #7097.
209+
self.aggregates = SortedDict() # See 18056.
208210
self.set_extra_mask([])
209211
self.distinct = True
210212
self.order_by = order == 'ASC' and [1] or [-1]

tests/modeltests/aggregation/tests.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,3 +565,23 @@ def test_annotate_values_list(self):
565565
(Decimal('82.8'), 1),
566566
]
567567
)
568+
569+
def test_dates_with_aggregation(self):
570+
"""
571+
Test that .dates() returns a distinct set of dates when applied to a
572+
QuerySet with aggregation.
573+
574+
Refs #18056. Previously, .dates() would return distinct (date_kind,
575+
aggregation) sets, in this case (year, num_authors), so 2008 would be
576+
returned twice because there are books from 2008 with a different
577+
number of authors.
578+
"""
579+
dates = Book.objects.annotate(num_authors=Count("authors")).dates('pubdate', 'year')
580+
self.assertQuerysetEqual(
581+
dates, [
582+
"datetime.datetime(1991, 1, 1, 0, 0)",
583+
"datetime.datetime(1995, 1, 1, 0, 0)",
584+
"datetime.datetime(2007, 1, 1, 0, 0)",
585+
"datetime.datetime(2008, 1, 1, 0, 0)"
586+
]
587+
)

0 commit comments

Comments
 (0)