Skip to content

Commit

Permalink
Merge pull request #2426 from volfpeter/master
Browse files Browse the repository at this point in the history
Fix LazyReferenceField dereferencing in embedded documents
  • Loading branch information
bagerard committed Nov 26, 2020
2 parents 904fcd1 + e0bec88 commit 277b827
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions mongoengine/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -2570,6 +2570,7 @@ def to_python(self, value):
if not isinstance(value, (DBRef, Document, EmbeddedDocument)):
collection = self.document_type._get_collection_name()
value = DBRef(collection, self.document_type.id.to_python(value))
value = self.build_lazyref(value)
return value

def validate(self, value):
Expand Down
45 changes: 45 additions & 0 deletions tests/fields/test_lazy_reference_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from mongoengine import *
from mongoengine.base import LazyReference
from mongoengine.context_managers import query_counter

from tests.utils import MongoDBTestCase

Expand Down Expand Up @@ -330,6 +331,50 @@ def check_fields_type(occ):
occ.in_embedded.in_list = [animal1.id, animal2.id]
check_fields_type(occ)

def test_lazy_reference_embedded_dereferencing(self):
# Test case for #2375

# -- Test documents

class Author(Document):
name = StringField()

class AuthorReference(EmbeddedDocument):
author = LazyReferenceField(Author)

class Book(Document):
authors = EmbeddedDocumentListField(AuthorReference)

# -- Cleanup

Author.drop_collection()
Book.drop_collection()

# -- Create test data

author_1 = Author(name="A1").save()
author_2 = Author(name="A2").save()
author_3 = Author(name="A3").save()
book = Book(
authors=[
AuthorReference(author=author_1),
AuthorReference(author=author_2),
AuthorReference(author=author_3),
]
).save()

with query_counter() as qc:
book = Book.objects.first()
# Accessing the list must not trigger dereferencing.
book.authors
assert qc == 1

for ref in book.authors:
with pytest.raises(AttributeError):
ref["author"].name
assert isinstance(ref.author, LazyReference)
assert isinstance(ref.author.id, ObjectId)


class TestGenericLazyReferenceField(MongoDBTestCase):
def test_generic_lazy_reference_simple(self):
Expand Down

0 comments on commit 277b827

Please sign in to comment.