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