Compare commits

...

2 Commits

Author SHA1 Message Date
Stefan Wojcik
2d9e21f639 one more test 2017-03-05 17:39:53 -05:00
Stefan Wojcik
4631b75553 respect db fields in multiple layers of embedded docs 2017-03-05 17:35:37 -05:00
2 changed files with 52 additions and 2 deletions

View File

@ -684,8 +684,13 @@ class BaseDocument(object):
# class if unavailable # class if unavailable
class_name = son.get('_cls', cls._class_name) class_name = son.get('_cls', cls._class_name)
# Convert SON to a dict, making sure each key is a string # Convert SON to a data dict, making sure each key is a string and
data = {str(key): value for key, value in son.iteritems()} # corresponds to the right db field.
data = {}
for key, value in son.iteritems():
key = str(key)
key = cls._db_field_map.get(key, key)
data[key] = value
# Return correct subclass for document type # Return correct subclass for document type
if class_name != cls._class_name: if class_name != cls._class_name:

View File

@ -1883,6 +1883,51 @@ class FieldTest(MongoDBTestCase):
doc = self.db.test.find_one() doc = self.db.test.find_one()
self.assertEqual(doc['x']['i'], 2) self.assertEqual(doc['x']['i'], 2)
def test_double_embedded_db_field(self):
"""Make sure multiple layers of embedded docs resolve db fields
properly and can be initialized using dicts.
"""
class C(EmbeddedDocument):
txt = StringField()
class B(EmbeddedDocument):
c = EmbeddedDocumentField(C, db_field='fc')
class A(Document):
b = EmbeddedDocumentField(B, db_field='fb')
a = A(
b=B(
c=C(txt='hi')
)
)
a.validate()
a = A(b={'c': {'txt': 'hi'}})
a.validate()
def test_double_embedded_db_field_from_son(self):
"""Make sure multiple layers of embedded docs resolve db fields
from SON properly.
"""
class C(EmbeddedDocument):
txt = StringField()
class B(EmbeddedDocument):
c = EmbeddedDocumentField(C, db_field='fc')
class A(Document):
b = EmbeddedDocumentField(B, db_field='fb')
a = A._from_son(SON([
('fb', SON([
('fc', SON([
('txt', 'hi')
]))
]))
]))
self.assertEqual(a.b.c.txt, 'hi')
def test_embedded_document_validation(self): def test_embedded_document_validation(self):
"""Ensure that invalid embedded documents cannot be assigned to """Ensure that invalid embedded documents cannot be assigned to
embedded document fields. embedded document fields.