From 55bcbd8d172b689811fae17cde2f09218dd74e9c Mon Sep 17 00:00:00 2001 From: Ekaterina Vahrusheva Date: Thu, 2 Mar 2023 21:38:05 +0300 Subject: [PATCH] Fixed #34378 -- Made QuerySet.in_bulk() not clear odering when id_list is passed. This reverts 340eaded4e30cf25bcd4e9781d33a617fe9c0f84. --- django/db/models/query.py | 4 ++-- tests/lookup/tests.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 71bb088679..6ac2a4cb10 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1108,9 +1108,9 @@ class QuerySet(AltersData): qs = () for offset in range(0, len(id_list), batch_size): batch = id_list[offset : offset + batch_size] - qs += tuple(self.filter(**{filter_key: batch}).order_by()) + qs += tuple(self.filter(**{filter_key: batch})) else: - qs = self.filter(**{filter_key: id_list}).order_by() + qs = self.filter(**{filter_key: id_list}) else: qs = self._chain() return {getattr(obj, field_name): obj for obj in qs} diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py index 53eb76d174..9778eaa5c5 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -246,6 +246,35 @@ class LookupTests(TestCase): with self.assertRaisesMessage(ValueError, msg): Article.objects.in_bulk([self.au1], field_name="author") + @skipUnlessDBFeature("can_distinct_on_fields") + def test_in_bulk_preserve_ordering(self): + articles = ( + Article.objects.order_by("author_id", "-pub_date") + .distinct("author_id") + .in_bulk([self.au1.id, self.au2.id], field_name="author_id") + ) + self.assertEqual( + articles, + {self.au1.id: self.a4, self.au2.id: self.a5}, + ) + + @skipUnlessDBFeature("can_distinct_on_fields") + def test_in_bulk_preserve_ordering_with_batch_size(self): + old_max_query_params = connection.features.max_query_params + connection.features.max_query_params = 1 + try: + articles = ( + Article.objects.order_by("author_id", "-pub_date") + .distinct("author_id") + .in_bulk([self.au1.id, self.au2.id], field_name="author_id") + ) + self.assertEqual( + articles, + {self.au1.id: self.a4, self.au2.id: self.a5}, + ) + finally: + connection.features.max_query_params = old_max_query_params + @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_distinct_field(self): self.assertEqual(