@@ -110,27 +110,37 @@ def join(self, compiler, connection):
110110 # In the lookup stage, the reference to this column doesn't include
111111 # the collection name.
112112 rhs_fields .append (rhs .as_mql (compiler , connection ))
113+ # Check if there are any extra conditions related to the join.
114+ # These are specific conditions that must be applied to the join beyond matching
115+ # field pairs (e.g., filtering based on additional criteria).
113116 extra = self .join_field .get_extra_restriction (self .table_alias , self .parent_alias )
114117 if extra :
115118 columns = []
116119 for expr in extra .leaves ():
120+ # Determine whether the column needs to be transformed or rerouted as part
121+ # of the subquery.
117122 for hand_side in ["lhs" , "rhs" ]:
118123 hand_side_value = getattr (expr , hand_side , None )
119124 if isinstance (hand_side_value , Col ):
125+ # If the column is not part of the joined table, add it to lhs_fields.
120126 if hand_side_value .alias != self .table_name :
121127 pos = len (lhs_fields )
122128 lhs_fields .append (expr .lhs .as_mql (compiler , connection ))
123129 else :
124130 pos = None
125131 columns .append ((hand_side_value , pos ))
132+ # Replace columns in the extra conditions with new column references
133+ # based on their rerouted positions in the join pipeline.
126134 replacements = {}
127135 for col , parent_pos in columns :
128- # Make all columns in as main collection columns.
129136 column_target = Col (compiler .collection_name , expr .output_field .__class__ ())
130137 if parent_pos is not None :
131138 column_target .target .db_column = f"${ parent_template } { parent_pos } "
132139 column_target .target .set_attributes_from_name (f"${ parent_template } { parent_pos } " )
140+ else :
141+ column_target .target = col .target
133142 replacements [col ] = column_target
143+ # Apply the transformed expressions in the extra condition.
134144 extra_condition = [extra .replace_expressions (replacements ).as_mql (compiler , connection )]
135145 else :
136146 extra_condition = []
0 commit comments