Skip to content

Commit 0239e86

Browse files
JaeHyuckSajacobtylerwalls
authored andcommitted
Fixed #36352 -- Improved error message for fields excluded by prior values()/values_list() calls.
Signed-off-by: JaeHyuck Sa <wogur981208@gmail.com>
1 parent a77e541 commit 0239e86

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

django/db/models/sql/query.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2585,10 +2585,17 @@ def set_values(self, fields):
25852585
annotation_names.append(f)
25862586
selected[f] = f
25872587
elif f in self.annotations:
2588-
raise FieldError(
2589-
f"Cannot select the '{f}' alias. Use annotate() to "
2590-
"promote it."
2591-
)
2588+
if self.annotation_select:
2589+
raise FieldError(
2590+
f"Cannot select the '{f}' alias. It was excluded "
2591+
f"by a previous values() or values_list() call. "
2592+
f"Include '{f}' in that call to select it."
2593+
)
2594+
else:
2595+
raise FieldError(
2596+
f"Cannot select the '{f}' alias. Use annotate() "
2597+
f"to promote it."
2598+
)
25922599
else:
25932600
# Call `names_to_path` to ensure a FieldError including
25942601
# annotations about to be masked as valid choices if

tests/annotations/tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,17 @@ def test_values_wrong_annotation(self):
482482
with self.assertRaisesMessage(FieldError, expected_message % article_fields):
483483
Book.objects.annotate(annotation=Value(1)).values_list("annotation_typo")
484484

485+
def test_chained_values_masked_annotation_error_message(self):
486+
msg = (
487+
"Cannot select the 'author_id' alias. It was excluded by a "
488+
"previous values() or values_list() call. Include 'author_id' in "
489+
"that call to select it."
490+
)
491+
with self.assertRaisesMessage(FieldError, msg):
492+
Book.objects.annotate(
493+
author_name=F("authors__name"), author_id=F("authors__id")
494+
).values("author_name").values("author_id")
495+
485496
def test_decimal_annotation(self):
486497
salary = Decimal(10) ** -Employee._meta.get_field("salary").decimal_places
487498
Employee.objects.create(

0 commit comments

Comments
 (0)