@@ -106,27 +106,37 @@ def join(self, compiler, connection):
106106 # In the lookup stage, the reference to this column doesn't include
107107 # the collection name.
108108 rhs_fields .append (rhs .as_mql (compiler , connection ))
109+ # Check if there are any extra conditions related to the join.
110+ # These are specific conditions that must be applied to the join beyond matching
111+ # field pairs (e.g., filtering based on additional criteria).
109112 extra = self .join_field .get_extra_restriction (self .table_alias , self .parent_alias )
110113 if extra :
111114 columns = []
112115 for expr in extra .leaves ():
116+ # Determine whether the column needs to be transformed or rerouted as part
117+ # of the subquery.
113118 for hand_side in ["lhs" , "rhs" ]:
114119 hand_side_value = getattr (expr , hand_side , None )
115120 if isinstance (hand_side_value , Col ):
121+ # If the column is not part of the joined table, add it to lhs_fields.
116122 if hand_side_value .alias != self .table_name :
117123 pos = len (lhs_fields )
118124 lhs_fields .append (expr .lhs .as_mql (compiler , connection ))
119125 else :
120126 pos = None
121127 columns .append ((hand_side_value , pos ))
128+ # Replace columns in the extra conditions with new column references
129+ # based on their rerouted positions in the join pipeline.
122130 replacements = {}
123131 for col , parent_pos in columns :
124- # Make all columns in as main collection columns.
125132 column_target = Col (compiler .collection_name , expr .output_field .__class__ ())
126133 if parent_pos is not None :
127134 column_target .target .db_column = f"${ parent_template } { parent_pos } "
128135 column_target .target .set_attributes_from_name (f"${ parent_template } { parent_pos } " )
136+ else :
137+ column_target .target = col .target
129138 replacements [col ] = column_target
139+ # Apply the transformed expressions in the extra condition.
130140 extra_condition = [extra .replace_expressions (replacements ).as_mql (compiler , connection )]
131141 else :
132142 extra_condition = []
0 commit comments