Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mongoengine/base/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ def _from_son(cls, son, _auto_dereference=True, only_fields=None, created=False)
# get the class name from the document, falling back to the given
# class if unavailable
class_name = son.get('_cls', cls._class_name)
data = dict(("%s" % key, value) for key, value in son.iteritems())
data = dict(("%s" % cls._db_field_map.get(key,key), value) for key, value in son.iteritems())

# Return correct subclass for document type
if class_name != cls._class_name:
Expand Down
49 changes: 49 additions & 0 deletions tests/document/db_fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
import sys
sys.path[0:0] = [""]
import unittest

from bson import SON
from mongoengine import *

__all__ = ("DbFieldParameterTest", )


class DbFieldParameterTest(unittest.TestCase):

def setUp(self):
# testcase from https://github.com/MongoEngine/mongoengine/issues/904
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to add a docstring to the class above describing exactly what this set of tests ensures. Otherwise, we're forcing every dev to look up a (somewhat poorly worded) GitHub ticket in order to learn what this is about.

self.data = {'b': {'c': [{'x': 1.0, 'y': 2.0}]}}
self.reference_son = SON([('fb', SON([('fc', [SON([('fx', 1.0), ('fy', 2.0)])])]))])

class C(EmbeddedDocument):
x = FloatField(db_field='fx')
y = FloatField(db_field='fy')

class B(EmbeddedDocument):
c = ListField(EmbeddedDocumentField(C), db_field='fc')

class A(Document):
b = EmbeddedDocumentField(B, db_field='fb')

self.A = A

def test_document_db_field_validation(self):
a = self.A(**self.data)
try:
a.validate()
except ValidationError as e:
self.fail("ValidationError raised: %s" % e.message)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to have try-except here. Can be replaced with a.validate() # the test passes if this doesn't raise a ValidationError.


def test_document_fieldname_to_db_field_name(self):
a = self.A(**self.data)
self.assertEqual(a.to_mongo(), self.reference_son)

def test_document_db_fieldname_to_fieldname(self):
a = self.A._from_son(self.reference_son)
self.assertEqual(a.b.c[0].x, 1.0)
self.assertEqual(a.b.c[0].y, 2.0)


if __name__ == '__main__':
unittest.main()