From e11d05e0b488a3ff2b3c9d8f2e1e50f471750d6e Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Mon, 14 Sep 2020 20:07:44 +0200 Subject: [PATCH] Fixed #31990 -- Fixed QuerySet.ordered for GROUP BY queries on models with Meta.ordering. Regression in 0ddb4ebf7bfcc4730c80a772dd146a49ef6895f6. Thanks Julien Dutriaux for the report. --- django/db/models/query.py | 7 ++++++- docs/releases/3.1.2.txt | 5 +++++ tests/queries/tests.py | 10 ++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 85cd8311a7..67ffe7f000 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1224,7 +1224,12 @@ class QuerySet: return True if self.query.extra_order_by or self.query.order_by: return True - elif self.query.default_ordering and self.query.get_meta().ordering: + elif ( + self.query.default_ordering and + self.query.get_meta().ordering and + # A default ordering doesn't affect GROUP BY queries. + not self.query.group_by + ): return True else: return False diff --git a/docs/releases/3.1.2.txt b/docs/releases/3.1.2.txt index 1243654bfb..f9e45370ab 100644 --- a/docs/releases/3.1.2.txt +++ b/docs/releases/3.1.2.txt @@ -11,3 +11,8 @@ Bugfixes * Fixed a bug in Django 3.1 where ``FileField`` instances with a callable storage were not correctly deconstructed (:ticket:`31941`). + +* Fixed a regression in Django 3.1 where the :attr:`.QuerySet.ordered` + attribute returned incorrectly ``True`` for ``GROUP BY`` queries (e.g. + ``.annotate().values()``) on models with ``Meta.ordering``. A model's + ``Meta.ordering`` doesn't affect such queries (:ticket:`31990`). diff --git a/tests/queries/tests.py b/tests/queries/tests.py index f9a57b088a..428153402f 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -2084,6 +2084,16 @@ class QuerysetOrderedTests(unittest.TestCase): self.assertIs(qs.ordered, False) self.assertIs(qs.order_by('num_notes').ordered, True) + def test_annotated_default_ordering(self): + qs = Tag.objects.annotate(num_notes=Count('pk')) + self.assertIs(qs.ordered, False) + self.assertIs(qs.order_by('name').ordered, True) + + def test_annotated_values_default_ordering(self): + qs = Tag.objects.values('name').annotate(num_notes=Count('pk')) + self.assertIs(qs.ordered, False) + self.assertIs(qs.order_by('name').ordered, True) + @skipUnlessDBFeature('allow_sliced_subqueries_with_in') class SubqueryTests(TestCase):