Skip to content

Commit 3ed605c

Browse files
authored
Merge pull request #2827 from bagerard/neolooong-patch
Fix weakref in EmbeddedDocumentListField
2 parents e5ec680 + 1e56b1f commit 3ed605c

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

mongoengine/base/datastructures.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,11 @@ def __init__(self, list_items, instance, name):
113113
BaseDocument = _import_class("BaseDocument")
114114

115115
if isinstance(instance, BaseDocument):
116-
self._instance = weakref.proxy(instance)
116+
if isinstance(instance, weakref.ProxyTypes):
117+
self._instance = instance
118+
else:
119+
self._instance = weakref.proxy(instance)
120+
117121
self._name = name
118122
super().__init__(list_items)
119123

@@ -186,10 +190,6 @@ def _mark_as_changed(self, key=None):
186190

187191

188192
class EmbeddedDocumentList(BaseList):
189-
def __init__(self, list_items, instance, name):
190-
super().__init__(list_items, instance, name)
191-
self._instance = instance
192-
193193
@classmethod
194194
def __match_all(cls, embedded_doc, kwargs):
195195
"""Return True if a given embedded doc matches all the filter

tests/fields/test_embedded_document_field.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import weakref
12
from copy import deepcopy
23

34
import pytest
@@ -62,6 +63,36 @@ class MyFailingDoc(Document):
6263
class MyFailingdoc2(Document):
6364
emb = EmbeddedDocumentField("MyDoc")
6465

66+
def test_embedded_document_list_field__has__instance_weakref(self):
67+
class Comment(EmbeddedDocument):
68+
content = StringField()
69+
70+
class Post(Document):
71+
title = StringField()
72+
comment = EmbeddedDocumentField(Comment)
73+
comments = EmbeddedDocumentListField(Comment)
74+
comments2 = ListField(EmbeddedDocumentField(Comment))
75+
76+
Post.drop_collection()
77+
78+
for i in range(5):
79+
Post(
80+
title=f"{i}",
81+
comment=Comment(content=f"{i}"),
82+
comments=[Comment(content=f"{i}")],
83+
comments2=[Comment(content=f"{i}")],
84+
).save()
85+
86+
posts = list(Post.objects)
87+
for post in posts:
88+
assert isinstance(post.comments._instance, weakref.ProxyTypes)
89+
assert isinstance(post.comments2._instance, weakref.ProxyTypes)
90+
assert isinstance(post.comment._instance, weakref.ProxyTypes)
91+
for comment in post.comments:
92+
assert isinstance(comment._instance, weakref.ProxyTypes)
93+
for comment2 in post.comments2:
94+
assert isinstance(comment2._instance, weakref.ProxyTypes)
95+
6596
def test_embedded_document_field_validate_subclass(self):
6697
class BaseItem(EmbeddedDocument):
6798
f = IntField()

0 commit comments

Comments
 (0)