On SQLAlchemy 2.1.0 or 2.1.1, Fixing an N+1 Could Change Your Results
The standard fix for an N+1 query in SQLAlchemy is to eager load the relationship with selectinload(). On SQLAlchemy 2.1.0 and 2.1.1, that fix can change your results. A regression in those two releases makes selectinload() ignore part of the join condition on some many-to-many relationships. The query gets faster, and it also returns related rows that the relationship was defined to exclude. It’s fixed in 2.1.2, released October 2.