diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 177bf6760d..4f09f73de3 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1373,7 +1373,7 @@ class Query(BaseExpression): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression( - self, allow_joins=allow_joins, summarize=summarize + self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize ) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py index 09b9453449..2dddd826e3 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -1357,6 +1357,9 @@ class LookupQueryingTests(TestCase): cls.s1 = Season.objects.create(year=1942, gt=1942) cls.s2 = Season.objects.create(year=1842, gt=1942, nulled_text_field="text") cls.s3 = Season.objects.create(year=2042, gt=1942) + Game.objects.create(season=cls.s1, home="NY", away="Boston") + Game.objects.create(season=cls.s1, home="NY", away="Tampa") + Game.objects.create(season=cls.s3, home="Boston", away="Tampa") def test_annotate(self): qs = Season.objects.annotate(equal=Exact(F("year"), 1942)) @@ -1527,3 +1530,19 @@ class LookupQueryingTests(TestCase): {"year": 2042, "century": "other"}, ], ) + + def test_multivalued_join_reuse(self): + self.assertEqual( + Season.objects.get(Exact(F("games__home"), "NY"), games__away="Boston"), + self.s1, + ) + self.assertEqual( + Season.objects.get(Exact(F("games__home"), "NY") & Q(games__away="Boston")), + self.s1, + ) + self.assertEqual( + Season.objects.get( + Exact(F("games__home"), "NY") & Exact(F("games__away"), "Boston") + ), + self.s1, + )