Skip to content

Fix m2m double filtering alias#2083

Merged
abondar merged 1 commit intodevelopfrom
fix/m2m-filtering
Feb 8, 2026
Merged

Fix m2m double filtering alias#2083
abondar merged 1 commit intodevelopfrom
fix/m2m-filtering

Conversation

@abondar
Copy link
Member

@abondar abondar commented Feb 8, 2026

Fixed bug where Model had 2 m2m fields to same model, so that filtering by both at the same time was improssible due to alias issues

Repacked version #1972
Fixes issue #1969

AI Summary:
This pull request improves support for filtering across multiple many-to-many (M2M) relationships to the same target table in the ORM. It ensures that queries involving multiple M2M relations from a single model to the same target produce correct and distinct SQL JOINs by introducing proper aliasing. The changes are validated with new tests and model definitions.

Query building and aliasing improvements:

  • Updated get_joins_for_related_field and resolve_nested_field in tortoise/query_utils.py to ensure that when filtering or joining on multiple M2M relations to the same target table, the generated SQL uses distinct aliases for each join, preventing conflicts and ensuring correct query results. [1] [2] [3]

Testing for M2M filtering and SQL generation:

  • Added new models Flavor and Drink to tests/testmodels.py, with Drink having two separate M2M relations to Flavor via flavors and toppings.
  • Added a test test_m2m_filter_multiple_relations_to_same_table in tests/test_filtering.py to verify that filtering on both M2M relations returns the correct results.
  • Added a test test_m2m_filter_two_relations_same_target_produces_aliased_joins in tests/test_sql.py to assert that the generated SQL contains the expected aliased JOINs for both MySQL and Postgres/SQLite dialects.

Test imports and setup:

  • Updated test imports in tests/test_filtering.py and tests/test_sql.py to include the new Drink and Flavor models. [1] [2]

@codspeed-hq
Copy link

codspeed-hq bot commented Feb 8, 2026

Merging this PR will not alter performance

✅ 24 untouched benchmarks


Comparing fix/m2m-filtering (2ace323) with develop (420d68b)

Open in CodSpeed

@coveralls
Copy link

Pull Request Test Coverage Report for Build 21799330042

Details

  • 4 of 4 (100.0%) changed or added relevant lines in 1 file are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.001%) to 82.331%

Totals Coverage Status
Change from base Build 21798872884: -0.001%
Covered Lines: 10192
Relevant Lines: 11916

💛 - Coveralls

@abondar abondar merged commit 2378386 into develop Feb 8, 2026
25 checks passed
@abondar abondar deleted the fix/m2m-filtering branch February 8, 2026 14:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments