|
4 | 4 | from django.core.exceptions import FieldDoesNotExist
|
5 | 5 | from django.db import models
|
6 | 6 | from django.db.models import lookups
|
| 7 | +from django.db.models.expressions import Col |
7 | 8 | from django.db.models.fields.related import lazy_related_operation
|
8 | 9 | from django.db.models.lookups import Transform
|
9 | 10 |
|
@@ -194,14 +195,22 @@ def get_conditions(self, emf_data, prefix):
|
194 | 195 | def as_mql(self, compiler, connection):
|
195 | 196 | lhs_mql = process_lhs(self, compiler, connection)
|
196 | 197 | value = process_rhs(self, compiler, connection)
|
197 |
| - if isinstance(value, models.Model): |
198 |
| - value, emf_data = self.model_to_dict(value) |
199 |
| - prefix = self.lhs.as_mql(compiler, connection) |
200 |
| - # Get conditions for top-level EmbeddedModelField. |
201 |
| - conditions = [{"$eq": [f"{prefix}.{k}", v]} for k, v in value.items()] |
202 |
| - # Get conditions for any nested EmbeddedModelFields. |
203 |
| - conditions += self.get_conditions(emf_data, prefix) |
204 |
| - return {"$and": conditions} |
| 198 | + if isinstance(self.lhs, Col) or ( |
| 199 | + isinstance(self.lhs, KeyTransform) |
| 200 | + and isinstance(self.lhs.ref_field, EmbeddedModelField) |
| 201 | + ): |
| 202 | + if isinstance(value, models.Model): |
| 203 | + value, emf_data = self.model_to_dict(value) |
| 204 | + prefix = self.lhs.as_mql(compiler, connection) |
| 205 | + # Get conditions for top-level EmbeddedModelField. |
| 206 | + conditions = [{"$eq": [f"{prefix}.{k}", v]} for k, v in value.items()] |
| 207 | + # Get conditions for any nested EmbeddedModelFields. |
| 208 | + conditions += self.get_conditions(emf_data, prefix) |
| 209 | + return {"$and": conditions} |
| 210 | + raise TypeError( |
| 211 | + "An EmbeddedModelField must be queried using a model instance, got %s." |
| 212 | + % type(value) |
| 213 | + ) |
205 | 214 | return connection.mongo_operators[self.lookup_name](lhs_mql, value)
|
206 | 215 |
|
207 | 216 |
|
|
0 commit comments