diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py index 46935c1b8..6be7e8226 100644 --- a/mongoengine/base/document.py +++ b/mongoengine/base/document.py @@ -470,6 +470,14 @@ def __expand_dynamic_values(self, name, value): # If the value is a dict with '_cls' in it, turn it into a document is_dict = isinstance(value, dict) if is_dict and "_cls" in value: + + # If the value is a referenced document, dereference it + if "_ref" in value: + _dereference = _import_class("DeReference")() + documents = _dereference([value]) + if documents: + return documents[0] + cls = get_document(value["_cls"]) return cls(**value) diff --git a/tests/test_dereference.py b/tests/test_dereference.py index bddcc5432..f34ca71dd 100644 --- a/tests/test_dereference.py +++ b/tests/test_dereference.py @@ -1352,6 +1352,28 @@ class Page(Document): page = Page.objects.first() assert page.tags[0] == page.posts[0].tags[0] + def test_dereferencing_dynamic_embedded_field_referencefield(self): + class Tag(Document): + meta = {"collection": "tags"} + name = StringField() + + class Post(DynamicEmbeddedDocument): + pass + + class Page(Document): + meta = {"collection": "pages"} + post = EmbeddedDocumentField(Post) + + Tag.drop_collection() + Page.drop_collection() + + tag = Tag(name="test").save() + post = Post(book_tag=tag) + Page(post=post).save() + + page = Page.objects.first() + assert page.post.book_tag == post.book_tag + def test_select_related_follows_embedded_referencefields(self): class Song(Document): title = StringField()