From a3bb80dc3186bd4d11b7864268beb88595ab00fd Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Mon, 14 Sep 2020 20:07:44 +0200 Subject: [PATCH] [3.1.x] Fixed #31990 -- Fixed QuerySet.ordered for GROUP BY queries on models with Meta.ordering. Regression in 0ddb4ebf7bfcc4730c80a772dd146a49ef6895f6. Thanks Julien Dutriaux for the report. Backport of e11d05e0b488a3ff2b3c9d8f2e1e50f471750d6e from master --- 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 e0eeccefa68..9c074772620 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1220,7 +1220,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 1243654bfb6..f9e45370ab9 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 faa443adb14..11d5ec11ab1 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -2074,6 +2074,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):