Skip to content

Commit bb7a770

Browse files
JaeHyuckSajacobtylerwalls
authored andcommitted
Fixed #36431 -- Returned tuples for multi-column ForeignObject in values()/values_list().
Thanks Jacob Walls and Simon Charette for tests. Signed-off-by: SaJH <wogur981208@gmail.com>
1 parent 2d453a2 commit bb7a770

3 files changed

Lines changed: 33 additions & 4 deletions

File tree

django/db/models/sql/query.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2269,8 +2269,21 @@ def add_fields(self, field_names, allow_m2m=True):
22692269
join_info.joins,
22702270
join_info.path,
22712271
)
2272-
for target in targets:
2273-
cols.append(join_info.transform_function(target, final_alias))
2272+
if len(targets) > 1:
2273+
transformed_targets = [
2274+
join_info.transform_function(target, final_alias)
2275+
for target in targets
2276+
]
2277+
cols.append(
2278+
ColPairs(
2279+
final_alias if self.alias_cols else None,
2280+
[col.target for col in transformed_targets],
2281+
[col.output_field for col in transformed_targets],
2282+
join_info.final_field,
2283+
)
2284+
)
2285+
else:
2286+
cols.append(join_info.transform_function(targets[0], final_alias))
22742287
if cols:
22752288
self.set_select(cols)
22762289
except MultiJoin:

docs/releases/5.2.6.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,6 @@ Django 5.2.6 fixes a security issue with severity "high" and several bugs in
1010
Bugfixes
1111
========
1212

13-
* ...
13+
* Fixed a bug where using ``QuerySet.values()`` or ``values_list()`` with a
14+
``ForeignObject`` composed of multiple fields returned incorrect results
15+
instead of tuples of the referenced fields (:ticket:`36431`).

tests/composite_pk/test_values.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from django.test import TestCase
55

6-
from .models import Post, Tenant, User
6+
from .models import Comment, Post, Tenant, User
77

88

99
class CompositePKValuesTests(TestCase):
@@ -210,3 +210,17 @@ def test_values(self):
210210
{"pk": self.user_3.pk, "id": self.user_3.id},
211211
),
212212
)
213+
214+
def test_foreign_object_values(self):
215+
Comment.objects.create(id=1, user=self.user_1, integer=42)
216+
testcases = {
217+
"all": Comment.objects.all(),
218+
"exclude_user_email": Comment.objects.exclude(user__email__endswith="net"),
219+
}
220+
for name, queryset in testcases.items():
221+
with self.subTest(name=name):
222+
values = list(queryset.values("user", "integer"))
223+
self.assertEqual(
224+
values[0]["user"], (self.user_1.tenant_id, self.user_1.id)
225+
)
226+
self.assertEqual(values[0]["integer"], 42)

0 commit comments

Comments
 (0)