Skip to content

Commit 438d9f7

Browse files
committed
add nested test
1 parent 94998a3 commit 438d9f7

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

tests/model_fields_/models.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ class Dog(EmbeddedModel):
239239
barks = models.BooleanField(default=True)
240240
created_at = models.DateTimeField(auto_now_add=True)
241241
updated_at = models.DateTimeField(auto_now=True)
242+
toys = PolymorphicEmbeddedModelField(["Bone"], blank=True, null=True)
242243

243244
def __str__(self):
244245
return self.name
@@ -248,6 +249,15 @@ class Cat(EmbeddedModel):
248249
name = models.CharField(max_length=100)
249250
purs = models.BooleanField(default=True)
250251
weight = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
252+
toys = PolymorphicEmbeddedModelField(["Mouse"], blank=True, null=True)
251253

252254
def __str__(self):
253255
return self.name
256+
257+
258+
class Bone(EmbeddedModel):
259+
brand = models.CharField(max_length=100)
260+
261+
262+
class Mouse(EmbeddedModel):
263+
manufacturer = models.CharField(max_length=100)

tests/model_fields_/test_polymorphic_embedded_model.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from django_mongodb_backend.fields import PolymorphicEmbeddedModelField
1010
from django_mongodb_backend.models import EmbeddedModel
1111

12-
from .models import Cat, Dog, Library, Person
12+
from .models import Bone, Cat, Dog, Library, Mouse, Person
1313
from .utils import truncate_ms
1414

1515

@@ -103,6 +103,7 @@ def setUpTestData(cls):
103103
pet=Cat(
104104
name=f"Cat {x}",
105105
weight=f"{x}.5",
106+
toys=Mouse(manufacturer=f"Maker {x}"),
106107
),
107108
)
108109
for x in range(6)
@@ -113,6 +114,7 @@ def setUpTestData(cls):
113114
pet=Dog(
114115
name=f"Dog {x}",
115116
barks=x % 2 == 0,
117+
toys=Bone(brand=f"Brand {x}"),
116118
),
117119
)
118120
for x in range(6)
@@ -148,6 +150,19 @@ def test_boolean(self):
148150
[x for i, x in enumerate(self.dog_owners) if i % 2 == 0],
149151
)
150152

153+
def test_nested(self):
154+
# Cat and Dog both have field toys = PolymorphicEmbeddedModelField(...)
155+
# but with different models. It's possible to query the fields of the
156+
# Dog's toys because it's the first model in Person.pet.
157+
self.assertCountEqual(
158+
Person.objects.filter(pet__toys__brand="Brand 1"),
159+
[self.dog_owners[1]],
160+
)
161+
# The fields of Cat can't be queried.
162+
msg = "The models of field 'toys' have no field named 'manufacturer'."
163+
with self.assertRaisesMessage(FieldDoesNotExist, msg):
164+
(Person.objects.filter(pet__toys__manufacturer="Maker 1"),)
165+
151166

152167
class InvalidLookupTests(SimpleTestCase):
153168
def test_invalid_field(self):

0 commit comments

Comments
 (0)