8000 Fixed #36416 -- Made QuerySet.in_bulk() account for composite pks in … · django/django@26313bc · GitHub
[go: up one dir, main page]

Skip to content

Commit 26313bc

Browse files
jacobtylerwallssarahboyce
authored andcommitted
Fixed #36416 -- Made QuerySet.in_bulk() account for composite pks in id_list.
1 parent 953095d commit 26313bc

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

django/db/models/query.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1180,7 +1180,9 @@ def in_bulk(self, id_list=None, *, field_name="pk"):
11801180
if not id_list:
11811181
return {}
11821182
filter_key = "{}__in".format(field_name)
1183-
batch_size = connections[self.db].features.max_query_params
1183+
max_params = connections[self.db].features.max_query_params or 0
1184+
num_fields = len(opts.pk_fields) if field_name == "pk" else 1
1185+
batch_size = max_params // num_fields
11841186
id_list = tuple(id_list)
11851187
# If the database has a limit on the number of query parameters
11861188
# (e.g. SQLite), retrieve objects in batches if necessary.

docs/releases/5.2.2.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,7 @@ Bugfixes
3434
* Fixed a regression in Django 5.2 where admin's ``filter_horizontal`` buttons
3535
lacked ``type="button"``, causing them to intercept form submission when
3636
pressing the Enter key (:ticket:`36423`).
37+
38+
* Fixed a bug in Django 5.2 where calling ``QuerySet.in_bulk()`` with an
39+
``id_list`` argument on models with a ``CompositePrimaryKey`` failed to
40+
observe database parameter limits (:ticket:`36416`).

tests/composite_pk/tests.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,22 @@ def test_in_bulk(self):
147147
result = Comment.objects.in_bulk([self.comment.pk])
148148
self.assertEqual(result, {self.comment.pk: self.comment})
149149

150+
@unittest.mock.patch.object(
151+
type(connection.features), "max_query_params", new_callable=lambda: 10
152+
)
153+
def test_in_bulk_batching(self, mocked_max_query_params):
154+
Comment.objects.all().delete()
155+
num_requiring_batching = (connection.features.max_query_params // 2) + 1
156+
comments = [
157+
Comment(id=i, tenant=self.tenant, user=self.user)
158+
for i in range(1, num_requiring_batching + 1)
159+
]
160+
Comment.objects.bulk_create(comments)
161+
id_list = list(Comment.objects.values_list("pk", flat=True))
162+
with self.assertNumQueries(2):
163+
comment_dict = Comment.objects.in_bulk(id_list=id_list)
164+
self.assertQuerySetEqual(comment_dict, id_list)
165+
150166
def test_iterator(self):
151167
"""
152168
Test the .iterator() method of composite_pk models.

0 commit comments

Comments
 (0)
0