Skip to content

Commit 9fb0d28

Browse files
committed
Allow querying an EmbeddedModelField by model instance
1 parent 12e293c commit 9fb0d28

File tree

5 files changed

+166
-10
lines changed

5 files changed

+166
-10
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):
@@ -151,6 +154,65 @@ def formfield(self, **kwargs):
151154
)
152155

153156

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

docs/source/releases/5.2.x.rst

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ New features
2020

2121
- Added :class:`.SearchIndex` and :class:`.VectorSearchIndex` for use on
2222
a model's :attr:`Meta.indexes <django.db.models.Options.indexes>`.
23+
- Allowed ``EmbeddedModelField``’s ``exact`` lookup to use a model instance.
2324

2425
Backwards incompatible changes
2526
------------------------------

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
@@ -138,3 +138,31 @@ class Library(models.Model):
138138

139139
def __str__(self):
140140
return self.name
141+
142+
143+
class A(models.Model):
144+
b = EmbeddedModelField("B")
145+
146+
147+
class B(EmbeddedModel):
148+
c = EmbeddedModelField("C")
149+
name = models.CharField(max_length=100)
150+
value = models.IntegerField()
151+
152+
153+
class C(EmbeddedModel):
154+
d = EmbeddedModelField("D")
155+
name = models.CharField(max_length=100)
156+
value = models.IntegerField()
157+
158+
159+
class D(EmbeddedModel):
160+
e = EmbeddedModelField("E")
161+
nullable_e = EmbeddedModelField("E", null=True, blank=True)
162+
name = models.CharField(max_length=100)
163+
value = models.IntegerField()
164+
165+
166+
class E(EmbeddedModel):
167+
name = models.CharField(max_length=100)
168+
value = models.IntegerField()

tests/model_fields_/test_embedded_model.py

+62-10
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,15 +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-
NestedData,
28-
)
20+
from .models import A, Address, Author, B, Book, C, D, Data, E, Holder, Library, NestedData
2921
from .utils import truncate_ms
3022

3123

@@ -145,6 +137,66 @@ def test_order_by_embedded_field(self):
145137
qs = Holder.objects.filter(data__integer__gt=3).order_by("-data__integer")
146138
self.assertSequenceEqual(qs, list(reversed(self.objs[4:])))
147139

140+
def test_exact_with_model(self):
141+
data = Holder.objects.first().data
142+
self.assertEqual(
143+
Holder.objects.filter(data=data).get().data.integer, self.objs[0].data.integer
144+
)
145+
146+
def test_exact_with_model_ignores_key_order(self):
147+
# Due to the possibility of schema changes or the reordering of a
148+
# model's fields, a lookup must work if an embedded document has its
149+
# keys in a different order than what's declared on the embedded model.
150+
connection.get_collection("model_fields__holder").insert_one(
151+
{
152+
"data": {
153+
"auto_now": None,
154+
"auto_now_add": None,
155+
"json_value": None,
156+
"integer": 100,
157+
}
158+
}
159+
)
160+
self.assertEqual(Holder.objects.filter(data=Data(integer=100)).get().data.integer, 100)
161+
162+
def test_exact_with_nested_model(self):
163+
address = Address(city="NYC", state="NY")
164+
author = Author(name="Shakespeare", age=55, address=address)
165+
obj = Book.objects.create(author=author)
166+
self.assertCountEqual(Book.objects.filter(author=author), [obj])
167+
self.assertCountEqual(Book.objects.filter(author__address=address), [obj])
168+
169+
def test_exact_with_deeply_nested_models(self):
170+
e1 = E(name="E1", value=5)
171+
d1 = D(name="D1", value=4, e=e1)
172+
c1 = C(name="C1", value=3, d=d1)
173+
b1 = B(name="B1", value=2, c=c1)
174+
a1 = A.objects.create(b=b1)
175+
e2 = E(name="E2", value=6)
176+
d2 = D(name="D2", value=4, e=e1, nullable_e=e2)
177+
c2 = C(name="C2", value=3, d=d2)
178+
b2 = B(name="B2", value=2, c=c2)
179+
a2 = A.objects.create(b=b2)
180+
self.assertCountEqual(A.objects.filter(b=b1), [a1])
181+
self.assertCountEqual(A.objects.filter(b__c=c1), [a1])
182+
self.assertCountEqual(A.objects.filter(b__c__d=d1), [a1])
183+
self.assertCountEqual(A.objects.filter(b__c__d__e=e1), [a1, a2])
184+
self.assertCountEqual(A.objects.filter(b=b2), [a2])
185+
self.assertCountEqual(A.objects.filter(b__c=c2), [a2])
186+
self.assertCountEqual(A.objects.filter(b__c__d=d2), [a2])
187+
self.assertCountEqual(A.objects.filter(b__c__d__nullable_e=e2), [a2])
188+
189+
def test_exact_validates_argument(self):
190+
msg = "An EmbeddedModelField must be queried using a model instance, got <class 'dict'>."
191+
with self.assertRaisesMessage(TypeError, msg):
192+
str(A.objects.filter(b={}))
193+
with self.assertRaisesMessage(TypeError, msg):
194+
str(A.objects.filter(b__c={}))
195+
with self.assertRaisesMessage(TypeError, msg):
196+
str(A.objects.filter(b__c__d={}))
197+
with self.assertRaisesMessage(TypeError, msg):
198+
str(A.objects.filter(b__c__d__e={}))
199+
148200
def test_embedded_json_field_lookups(self):
149201
objs = [
150202
Holder.objects.create(

0 commit comments

Comments
 (0)