Skip to content

Commit 994dc6d

Browse files
jacobtylerwallssarahboyce
authored andcommitted
Fixed #36392 -- Raised ValueError when subquery referencing composite pk selects too many columns.
1 parent e03e5c7 commit 994dc6d

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

django/db/models/sql/query.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1227,7 +1227,10 @@ def add_annotation(self, annotation, alias, select=True):
12271227
@property
12281228
def _subquery_fields_len(self):
12291229
if self.has_select_fields:
1230-
return len(self.selected)
1230+
return sum(
1231+
len(self.model._meta.pk_fields) if field == "pk" else 1
1232+
for field in self.selected
1233+
)
12311234
return len(self.model._meta.pk_fields)
12321235

12331236
def resolve_expression(self, query, *args, **kwargs):

docs/releases/5.2.2.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,7 @@ Bugfixes
1111

1212
* Fixed a crash when using ``select_related`` against a ``ForeignObject``
1313
originating from a model with a ``CompositePrimaryKey`` (:ticket:`36373`).
14+
15+
* Fixed a bug in Django 5.2 where subqueries using ``"pk"`` to reference models
16+
with a ``CompositePrimaryKey`` failed to raise ``ValueError`` when too many
17+
or too few columns were selected (:ticket:`36392`).

tests/composite_pk/test_filter.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,14 @@ def test_filter_comments_by_pk_in_subquery(self):
206206
[self.comment_1],
207207
)
208208

209+
def test_filter_by_pk_in_subquery_invalid_selected_columns(self):
210+
msg = (
211+
"The QuerySet value for the 'in' lookup must have 2 selected "
212+
"fields (received 3)"
213+
)
214+
with self.assertRaisesMessage(ValueError, msg):
215+
Comment.objects.filter(pk__in=Comment.objects.values("pk", "text"))
216+
209217
def test_filter_by_pk_in_none(self):
210218
with self.assertNumQueries(0):
211219
self.assertSequenceEqual(

0 commit comments

Comments
 (0)