Hi all, my PR for ticket #16603 has been open for about two weeks and I’d welcome a review, especially from someone familiar with Query.build_filter() and join reuse.
Filtering on a multi-valued relation after annotate() adds a second join, so Count()/Sum() come back inflated. The PR also builds an equivalent pk IN (SELECT pk ...) subquery for such filters, and the compiler uses it when no other clause references the join; otherwise the join is kept as today.
About 280 lines touch sql/query.py, compiler.py and where.py; the rest is tests and docs. The suite passes on SQLite, PostgreSQL 17 and MySQL 8.4, with benchmarks in the PR. Feedback on the approach itself would be most useful at this stage.
PR: Fixed #16603 -- Avoided duplicate joins in filter() after aggregation. by Piergiuseppe · Pull Request #22207 · django/django · GitHub
Ticket: #16603 (Unnecessary join when using a reverse foreign-key filter and reverse foreign-key aggregate call) – Django