Skip to content

Commit 3f9288e

Browse files
committed
Allow querying an EmbeddedModelField by model instance
1 parent 782feb7 commit 3f9288e

File tree

5 files changed

+172
-9
lines changed

5 files changed

+172
-9
lines changed

django_mongodb_backend/fields/embedded_model.py

+62
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
from django.core import checks
44
from django.core.exceptions import FieldDoesNotExist
55
from django.db import models
6+
from django.db.models import lookups
7+
from django.db.models.expressions import Col
68
from django.db.models.fields.related import lazy_related_operation
79
from django.db.models.lookups import Transform
810

911
from .. import forms
12+
from ..query_utils import process_lhs, process_rhs
1013

1114

1215
class EmbeddedModelField(models.Field):
@@ -148,6 +151,65 @@ def formfield(self, **kwargs):
148151
)
149152

150153

154+
@EmbeddedModelField.register_lookup
155+
class EMFExact(lookups.Exact):
156+
def model_to_dict(self, instance):
157+
"""
158+
Return a dict containing the data in a model instance, as well as a
159+
dict containing the data for any embedded model fields.
160+
"""
161+
data = {}
162+
emf_data = {}
163+
for f in instance._meta.concrete_fields:
164+
value = f.value_from_object(instance)
165+
if isinstance(f, EmbeddedModelField):
166+
emf_data[f.name] = self.model_to_dict(value) if value is not None else (None, {})
167+
continue
168+
# Unless explicitly set, primary keys aren't included in embedded
169+
# models.
170+
if f.primary_key and value is None:
171+
continue
172+
data[f.name] = value
173+
return data, emf_data
174+
175+
def get_conditions(self, emf_data, prefix=None):
176+
"""
177+
Recursively transform a dictionary of {"field_name": {<model_to_dict>}}
178+
lookups into MQL. `prefix` tracks the string that must be appended to
179+
nested fields.
180+
"""
181+
conditions = []
182+
for k, v in emf_data.items():
183+
v, emf_data = v
184+
subprefix = f"{prefix}.{k}" if prefix else k
185+
conditions += self.get_conditions(emf_data, subprefix)
186+
if v is not None:
187+
# Match all field of the EmbeddedModelField.
188+
conditions += [{"$eq": [f"{subprefix}.{x}", y]} for x, y in v.items()]
189+
else:
190+
# Match a null EmbeddedModelField.
191+
conditions += [{"$eq": [f"{subprefix}", None]}]
192+
return conditions
193+
194+
def as_mql(self, compiler, connection):
195+
lhs_mql = process_lhs(self, compiler, connection)
196+
value = process_rhs(self, compiler, connection)
197+
if isinstance(self.lhs, Col) or (
198+
isinstance(self.lhs, KeyTransform)
199+
and isinstance(self.lhs.ref_field, EmbeddedModelField)
200+
):
201+
if isinstance(value, models.Model):
202+
value, emf_data = self.model_to_dict(value)
203+
# Get conditions for any nested EmbeddedModelFields.
204+
conditions = self.get_conditions({lhs_mql: (value, emf_data)})
205+
return {"$and": conditions}
206+
raise TypeError(
207+
"An EmbeddedModelField must be queried using a model instance, got %s."
208+
% type(value)
209+
)
210+
return connection.mongo_operators[self.lookup_name](lhs_mql, value)
211+
212+
151213
class KeyTransform(Transform):
152214
def __init__(self, key_name, ref_field, *args, **kwargs):
153215
super().__init__(*args, **kwargs)

docs/source/releases/5.2.x.rst

+7
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ Initial release from the state of :ref:`django-mongodb-backend 5.1.0 beta 2
1313
Regarding new features in Django 5.2,
1414
:class:`~django.db.models.CompositePrimaryKey` isn't supported.
1515

16+
New features
17+
------------
18+
19+
*These features won't appear in Django MongoDB Backend 5.1.x.*
20+
21+
- Allowed ``EmbeddedModelField``’s ``exact`` lookup to use a model instance.
22+
1623
Bug fixes
1724
---------
1825

docs/source/topics/embedded-models.rst

+13
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,16 @@ as relational fields. For example, to retrieve all customers who have an
5454
address with the city "New York"::
5555

5656
>>> Customer.objects.filter(address__city="New York")
57+
58+
You can also query using a model instance. Unlike a normal relational lookup
59+
which does the lookup by primary key, since embedded models typically don't
60+
have a primary key set, the query requires that every field match. For example,
61+
this query gives customers with addresses with the city "New York" and all
62+
other fields of the address equal to their default (:attr:`Field.default
63+
<django.db.models.Field.default>`, ``None``, or an empty string).
64+
65+
>>> Customer.objects.filter(address=Address(city="New York"))
66+
67+
.. versionadded:: 5.2.0b0
68+
69+
The ability to query by model instance was added.

tests/model_fields_/models.py

+28
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,31 @@ class Library(models.Model):
132132

133133
def __str__(self):
134134
return self.name
135+
136+
137+
class A(models.Model):
138+
b = EmbeddedModelField("B")
139+
140+
141+
class B(EmbeddedModel):
142+
c = EmbeddedModelField("C")
143+
name = models.CharField(max_length=100)
144+
value = models.IntegerField()
145+
146+
147+
class C(EmbeddedModel):
148+
d = EmbeddedModelField("D")
149+
name = models.CharField(max_length=100)
150+
value = models.IntegerField()
151+
152+
153+
class D(EmbeddedModel):
154+
e = EmbeddedModelField("E")
155+
nullable_e = EmbeddedModelField("E", null=True, blank=True)
156+
name = models.CharField(max_length=100)
157+
value = models.IntegerField()
158+
159+
160+
class E(EmbeddedModel):
161+
name = models.CharField(max_length=100)
162+
value = models.IntegerField()

tests/model_fields_/test_embedded_model.py

+62-9
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from datetime import timedelta
33

44
from django.core.exceptions import FieldDoesNotExist, ValidationError
5-
from django.db import models
5+
from django.db import connection, models
66
from django.db.models import (
77
Exists,
88
ExpressionWrapper,
@@ -17,14 +17,7 @@
1717
from django_mongodb_backend.fields import EmbeddedModelField
1818
from django_mongodb_backend.models import EmbeddedModel
1919

20-
from .models import (
21-
Address,
22-
Author,
23-
Book,
24-
Data,
25-
Holder,
26-
Library,
27-
)
20+
from .models import A, Address, Author, B, Book, C, D, Data, E, Holder, Library
2821
from .utils import truncate_ms
2922

3023

@@ -117,6 +110,66 @@ def test_order_by_embedded_field(self):
117110
qs = Holder.objects.filter(data__integer__gt=3).order_by("-data__integer")
118111
self.assertSequenceEqual(qs, list(reversed(self.objs[4:])))
119112

113+
def test_exact_with_model(self):
114+
data = Holder.objects.first().data
115+
self.assertEqual(
116+
Holder.objects.filter(data=data).get().data.integer, self.objs[0].data.integer
117+
)
118+
119+
def test_exact_with_model_ignores_key_order(self):
120+
# Due to the possibility of schema changes or the reordering of a
121+
# model's fields, a lookup must work if an embedded document has its
122+
# keys in a different order than what's declared on the embedded model.
123+
connection.get_collection("model_fields__holder").insert_one(
124+
{
125+
"data": {
126+
"auto_now": None,
127+
"auto_now_add": None,
128+
"json_value": None,
129+
"integer": 100,
130+
}
131+
}
132+
)
133+
self.assertEqual(Holder.objects.filter(data=Data(integer=100)).get().data.integer, 100)
134+
135+
def test_exact_with_nested_model(self):
136+
address = Address(city="NYC", state="NY")
137+
author = Author(name="Shakespeare", age=55, address=address)
138+
obj = Book.objects.create(author=author)
139+
self.assertCountEqual(Book.objects.filter(author=author), [obj])
140+
self.assertCountEqual(Book.objects.filter(author__address=address), [obj])
141+
142+
def test_exact_with_deeply_nested_models(self):
143+
e1 = E(name="E1", value=5)
144+
d1 = D(name="D1", value=4, e=e1)
145+
c1 = C(name="C1", value=3, d=d1)
146+
b1 = B(name="B1", value=2, c=c1)
147+
a1 = A.objects.create(b=b1)
148+
e2 = E(name="E2", value=6)
149+
d2 = D(name="D2", value=4, e=e1, nullable_e=e2)
150+
c2 = C(name="C2", value=3, d=d2)
151+
b2 = B(name="B2", value=2, c=c2)
152+
a2 = A.objects.create(b=b2)
153+
self.assertCountEqual(A.objects.filter(b=b1), [a1])
154+
self.assertCountEqual(A.objects.filter(b__c=c1), [a1])
155+
self.assertCountEqual(A.objects.filter(b__c__d=d1), [a1])
156+
self.assertCountEqual(A.objects.filter(b__c__d__e=e1), [a1, a2])
157+
self.assertCountEqual(A.objects.filter(b=b2), [a2])
158+
self.assertCountEqual(A.objects.filter(b__c=c2), [a2])
159+
self.assertCountEqual(A.objects.filter(b__c__d=d2), [a2])
160+
self.assertCountEqual(A.objects.filter(b__c__d__nullable_e=e2), [a2])
161+
162+
def test_exact_validates_argument(self):
163+
msg = "An EmbeddedModelField must be queried using a model instance, got <class 'dict'>."
164+
with self.assertRaisesMessage(TypeError, msg):
165+
str(A.objects.filter(b={}))
166+
with self.assertRaisesMessage(TypeError, msg):
167+
str(A.objects.filter(b__c={}))
168+
with self.assertRaisesMessage(TypeError, msg):
169+
str(A.objects.filter(b__c__d={}))
170+
with self.assertRaisesMessage(TypeError, msg):
171+
str(A.objects.filter(b__c__d__e={}))
172+
120173
def test_embedded_json_field_lookups(self):
121174
objs = [
122175
Holder.objects.create(

0 commit comments

Comments
 (0)