diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index a562a3db38..c0bcc1b3bf 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -471,6 +471,14 @@ class IntegerLessThanOrEqual(IntegerFieldOverflow, LessThanOrEqual): class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "in" + def get_refs(self): + refs = super().get_refs() + if self.rhs_is_direct_value(): + for rhs in self.rhs: + if get_rhs_refs := getattr(rhs, "get_refs", None): + refs |= get_rhs_refs() + return refs + def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index f04b1c4cc3..f50e012f82 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1268,7 +1268,7 @@ class Query(BaseExpression): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( - self.resolve_lookup_value(sub_value, can_reuse, allow_joins) + self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize) for sub_value in value ) type_ = type(value) diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index af6c660cf1..b01df88109 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -2315,3 +2315,9 @@ class AggregateAnnotationPruningTests(TestCase): max_book_author=Max("book__authors"), ).aggregate(count=Count("id", filter=Q(id=F("max_book_author")))) self.assertEqual(aggregates, {"count": 1}) + + def test_aggregate_reference_lookup_rhs_iter(self): + aggregates = Author.objects.annotate( + max_book_author=Max("book__authors"), + ).aggregate(count=Count("id", filter=Q(id__in=[F("max_book_author"), 0]))) + self.assertEqual(aggregates, {"count": 1})