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(