@@ -110,27 +110,37 @@ def join(self, compiler, connection):
110
110
# In the lookup stage, the reference to this column doesn't include
111
111
# the collection name.
112
112
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).
113
116
extra = self .join_field .get_extra_restriction (self .table_alias , self .parent_alias )
114
117
if extra :
115
118
columns = []
116
119
for expr in extra .leaves ():
120
+ # Determine whether the column needs to be transformed or rerouted as part
121
+ # of the subquery.
117
122
for hand_side in ["lhs" , "rhs" ]:
118
123
hand_side_value = getattr (expr , hand_side , None )
119
124
if isinstance (hand_side_value , Col ):
125
+ # If the column is not part of the joined table, add it to lhs_fields.
120
126
if hand_side_value .alias != self .table_name :
121
127
pos = len (lhs_fields )
122
128
lhs_fields .append (expr .lhs .as_mql (compiler , connection ))
123
129
else :
124
130
pos = None
125
131
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.
126
134
replacements = {}
127
135
for col , parent_pos in columns :
128
- # Make all columns in as main collection columns.
129
136
column_target = Col (compiler .collection_name , expr .output_field .__class__ ())
130
137
if parent_pos is not None :
131
138
column_target .target .db_column = f"${ parent_template } { parent_pos } "
132
139
column_target .target .set_attributes_from_name (f"${ parent_template } { parent_pos } " )
140
+ else :
141
+ column_target .target = col .target
133
142
replacements [col ] = column_target
143
+ # Apply the transformed expressions in the extra condition.
134
144
extra_condition = [extra .replace_expressions (replacements ).as_mql (compiler , connection )]
135
145
else :
136
146
extra_condition = []
0 commit comments