From 0239e86f387127dace7273208c300b33a065e021 Mon Sep 17 00:00:00 2001 From: JaeHyuck Sa Date: Fri, 16 Jan 2026 00:29:25 +0900 Subject: Fixed #36352 -- Improved error message for fields excluded by prior values()/values_list() calls. Signed-off-by: JaeHyuck Sa --- django/db/models/sql/query.py | 15 +++++++++++---- tests/annotations/tests.py | 11 +++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index e3e6100f24..4be450167d 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -2585,10 +2585,17 @@ class Query(BaseExpression): annotation_names.append(f) selected[f] = f elif f in self.annotations: - raise FieldError( - f"Cannot select the '{f}' alias. Use annotate() to " - "promote it." - ) + if self.annotation_select: + raise FieldError( + f"Cannot select the '{f}' alias. It was excluded " + f"by a previous values() or values_list() call. " + f"Include '{f}' in that call to select it." + ) + else: + raise FieldError( + f"Cannot select the '{f}' alias. Use annotate() " + f"to promote it." + ) else: # Call `names_to_path` to ensure a FieldError including # annotations about to be masked as valid choices if diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py index 6336cabafa..69a2b4a7c7 100644 --- a/tests/annotations/tests.py +++ b/tests/annotations/tests.py @@ -482,6 +482,17 @@ class NonAggregateAnnotationTestCase(TestCase): with self.assertRaisesMessage(FieldError, expected_message % article_fields): Book.objects.annotate(annotation=Value(1)).values_list("annotation_typo") + def test_chained_values_masked_annotation_error_message(self): + msg = ( + "Cannot select the 'author_id' alias. It was excluded by a " + "previous values() or values_list() call. Include 'author_id' in " + "that call to select it." + ) + with self.assertRaisesMessage(FieldError, msg): + Book.objects.annotate( + author_name=F("authors__name"), author_id=F("authors__id") + ).values("author_name").values("author_id") + def test_decimal_annotation(self): salary = Decimal(10) ** -Employee._meta.get_field("salary").decimal_places Employee.objects.create( -- cgit v1.3