﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
36029	Deep conditions in FilteredRelation raise ProgrammingError if annotation reused	Jacob Walls		"I was debugging a query that failed like this:
{{{#!py
psycopg.errors.UndefinedTable: missing FROM-clause entry for table ""book_editor""
LINE 1: ...r"" LEFT OUTER JOIN ""filtered_relation_editor"" ON (book_edito...
}}}

#33929 seems related. Here, the key is using a deeper condition relation (`book__editor`) than the filtered relation (`book`) and then reusing that attempted annotation in another `annotate()`.

Failing unit test. The test right above [https://github.com/django/django/blob/f05edb2b43c347d4929efd52c8e2b4e08839f542/tests/filtered_relation/tests.py#L624-L635 asserts] that a ValueError is raised in a similar situation, so maybe this test should do that also?

{{{#!diff
diff --git a/tests/filtered_relation/tests.py b/tests/filtered_relation/tests.py
index 82caba8662..e15efb447b 100644
--- a/tests/filtered_relation/tests.py
+++ b/tests/filtered_relation/tests.py
@@ -668,6 +668,15 @@ class FilteredRelationTests(TestCase):
                 ),
             )
 
+    def test_condition_deeper_relation_name_reused_annotation(self):
+        qs = Author.objects.annotate(
+            book_editor=FilteredRelation(
+                ""book"",
+                condition=Q(book__editor__name=""b""),
+            ),
+        ).annotate(reused_annotation=F(""book_editor""))
+        self.assertEqual(qs.count(), 2)
+
     def test_with_empty_relation_name_error(self):
         with self.assertRaisesMessage(ValueError, ""relation_name cannot be empty.""):
             FilteredRelation("""", condition=Q(blank=""""))
}}}"	Bug	new	Database layer (models, ORM)	5.1	Normal				Unreviewed	0	0	0	0	0	0
