Skip to content

Commit ea3a71c

Browse files
michalnikcharettes
authored andcommitted
Fixed #26434 -- Removed faulty clearing of ordering field when missing from explicit grouping.
Co-authored-by: Simon Charette <charette.s@gmail.com>
1 parent 0ea0110 commit ea3a71c

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

django/db/models/sql/query.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2346,7 +2346,13 @@ def clear_ordering(self, force=False, clear_default=True):
23462346
query (not even the model's default).
23472347
"""
23482348
if not force and (
2349-
self.is_sliced or self.distinct_fields or self.select_for_update
2349+
self.is_sliced
2350+
or self.distinct_fields
2351+
or self.select_for_update
2352+
or (
2353+
isinstance(self.group_by, tuple)
2354+
and not {*self.order_by, *self.extra_order_by}.issubset(self.group_by)
2355+
)
23502356
):
23512357
return
23522358
self.order_by = ()

tests/aggregation_regress/tests.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,25 @@ def assertObjectAttrs(self, obj, **kwargs):
171171
for attr, value in kwargs.items():
172172
self.assertEqual(getattr(obj, attr), value)
173173

174+
def test_count_preserve_group_by(self):
175+
# new release of the same book
176+
Book.objects.create(
177+
isbn="113235613",
178+
name=self.b4.name,
179+
pages=self.b4.pages,
180+
rating=4.0,
181+
price=Decimal("39.69"),
182+
contact=self.a5,
183+
publisher=self.p3,
184+
pubdate=datetime.date(2018, 11, 3),
185+
)
186+
qs = Book.objects.values("contact__name", "publisher__name").annotate(
187+
publications=Count("id")
188+
)
189+
self.assertEqual(qs.count(), Book.objects.count() - 1)
190+
self.assertEqual(qs.order_by("id").count(), Book.objects.count())
191+
self.assertEqual(qs.extra(order_by=["id"]).count(), Book.objects.count())
192+
174193
def test_annotation_with_value(self):
175194
values = (
176195
Book.objects.filter(

0 commit comments

Comments
 (0)