[3.1.x] Fixed #31990 -- Fixed QuerySet.ordered for GROUP BY queries on models with Meta.ordering.

Regression in 0ddb4ebf7b.

Thanks Julien Dutriaux for the report.
Backport of e11d05e0b4 from master
This commit is contained in:
Mariusz Felisiak 2020-09-14 20:07:44 +02:00
parent 462d7837f9
commit a3bb80dc31
3 changed files with 21 additions and 1 deletions

View File

@ -1220,7 +1220,12 @@ class QuerySet:
return True return True
if self.query.extra_order_by or self.query.order_by: if self.query.extra_order_by or self.query.order_by:
return True 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 return True
else: else:
return False return False

View File

@ -11,3 +11,8 @@ Bugfixes
* Fixed a bug in Django 3.1 where ``FileField`` instances with a callable * Fixed a bug in Django 3.1 where ``FileField`` instances with a callable
storage were not correctly deconstructed (:ticket:`31941`). 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`).

View File

@ -2074,6 +2074,16 @@ class QuerysetOrderedTests(unittest.TestCase):
self.assertIs(qs.ordered, False) self.assertIs(qs.ordered, False)
self.assertIs(qs.order_by('num_notes').ordered, True) 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') @skipUnlessDBFeature('allow_sliced_subqueries_with_in')
class SubqueryTests(TestCase): class SubqueryTests(TestCase):