SQLAlchemy 2.0 Select API migration for with_polymorphic loading
0 reputation · 06 Aug 2024, 11:58 UTC
Transitioning from Legacy Query to Select API
SQLAlchemy 2.0 replaces the legacy Session.query() pattern with a unified select() function. While most ORM operations have direct equivalents in the new Select object, certain advanced loading strategies used in polymorphic inheritance require a different approach.
Polymorphic Loading Constraints
In the legacy Query API, with_polymorphic() allowed for the explicit loading of multiple subclasses in a single query. In the 2.0-style API, there is no direct Select.with_polymorphic() method. Developers must currently rely on with_loader_criteria() or explicit joins to achieve similar results, but these methods handle the underlying SQL generation differently.
When migrating a codebase from version 1.4 (with future=True) to 2.0, the lack of a dedicated polymorphic method on the Select object creates uncertainty regarding the most efficient way to maintain complex inheritance queries without reverting to legacy patterns.
- Is
with_loader_criteria()intended to be the primary replacement forwith_polymorphic()in all 2.0 use cases? - What is the recommended pattern for implementing polymorphic loading when
with_loader_criteria()does not provide the necessary join control?