@@ -44,7 +44,7 @@ class RelationshipFilteringInfo(BaseModel):
4444 target_schema : Type [TypeSchema ]
4545 model : Type [TypeModel ]
4646 aliased_model : AliasedClass
47- column : InstrumentedAttribute
47+ join_column : InstrumentedAttribute
4848
4949 class Config :
5050 arbitrary_types_allowed = True
@@ -330,8 +330,9 @@ def gather_relationships_info(
330330 model : Type [TypeModel ],
331331 schema : Type [TypeSchema ],
332332 relationship_path : List [str ],
333- collected_info : dict ,
333+ collected_info : dict [ RelationshipPath , RelationshipFilteringInfo ] ,
334334 target_relationship_idx : int = 0 ,
335+ prev_aliased_model : Optional [Any ] = None ,
335336) -> dict [RelationshipPath , RelationshipFilteringInfo ]:
336337 is_last_relationship = target_relationship_idx == len (relationship_path ) - 1
337338 target_relationship_path = RELATIONSHIP_SPLITTER .join (
@@ -345,25 +346,36 @@ def gather_relationships_info(
345346
346347 target_schema = schema .__fields__ [target_relationship_name ].type_
347348 target_model = getattr (model , target_relationship_name ).property .mapper .class_
348- target_column = get_model_column (
349- model ,
350- schema ,
351- target_relationship_name ,
352- )
349+
350+ if prev_aliased_model :
351+ join_column = get_model_column (
352+ model = prev_aliased_model ,
353+ schema = schema ,
354+ field_name = target_relationship_name ,
355+ )
356+ else :
357+ join_column = get_model_column (
358+ model ,
359+ schema ,
360+ target_relationship_name ,
361+ )
362+
363+ aliased_model = aliased (target_model )
353364 collected_info [target_relationship_path ] = RelationshipFilteringInfo (
354365 target_schema = target_schema ,
355366 model = target_model ,
356- aliased_model = aliased ( target_model ) ,
357- column = target_column ,
367+ aliased_model = aliased_model ,
368+ join_column = join_column ,
358369 )
359370
360371 if not is_last_relationship :
361372 return gather_relationships_info (
362- target_model ,
363- target_schema ,
364- relationship_path ,
365- collected_info ,
366- target_relationship_idx + 1 ,
373+ model = target_model ,
374+ schema = target_schema ,
375+ relationship_path = relationship_path ,
376+ collected_info = collected_info ,
377+ target_relationship_idx = target_relationship_idx + 1 ,
378+ prev_aliased_model = aliased_model ,
367379 )
368380
369381 return collected_info
@@ -556,5 +568,5 @@ def create_filters_and_joins(
556568 target_schema = schema ,
557569 relationships_info = relationships_info ,
558570 )
559- joins = [(info .aliased_model , info .column ) for info in relationships_info .values ()]
571+ joins = [(info .aliased_model , info .join_column ) for info in relationships_info .values ()]
560572 return expressions , joins
0 commit comments