From b085993901e57797bdf8944e86a8a2611ac1e823 Mon Sep 17 00:00:00 2001 From: "Brian J. Dowling" Date: Mon, 27 Jan 2014 23:05:29 +0000 Subject: [PATCH 1/2] Allow dynamic dictionary-style field access Allows the doc[key] syntax to work for dynamicembeddeddocument fields Fixes #559 --- mongoengine/base/document.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py index f5eae8ff..c5ef087c 100644 --- a/mongoengine/base/document.py +++ b/mongoengine/base/document.py @@ -182,7 +182,7 @@ class BaseDocument(object): """Dictionary-style field access, set a field's value. """ # Ensure that the field exists before settings its value - if name not in self._fields: + if not self._dynamic and name not in self._fields: raise KeyError(name) return setattr(self, name, value) From 9b2080d036859c4456fc56c3085a14e791853035 Mon Sep 17 00:00:00 2001 From: "Brian J. Dowling" Date: Tue, 28 Jan 2014 22:10:26 -0500 Subject: [PATCH 2/2] Added a test for allowing dynamic dictionary-style field access Closes #559 --- tests/document/dynamic.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/document/dynamic.py b/tests/document/dynamic.py index 6263e68c..bf69cb27 100644 --- a/tests/document/dynamic.py +++ b/tests/document/dynamic.py @@ -292,6 +292,44 @@ class DynamicTest(unittest.TestCase): person.save() self.assertEqual(Person.objects.first().age, 35) + def test_dynamic_and_embedded_dict_access(self): + """Ensure embedded dynamic documents work with dict[] style access""" + + class Address(EmbeddedDocument): + city = StringField() + + class Person(DynamicDocument): + name = StringField() + + Person.drop_collection() + + Person(name="Ross", address=Address(city="London")).save() + + person = Person.objects.first() + person.attrval = "This works" + + person["phone"] = "555-1212" # but this should too + + # Same thing two levels deep + person["address"]["city"] = "Lundenne" + person.save() + + self.assertEqual(Person.objects.first().address.city, "Lundenne") + + self.assertEqual(Person.objects.first().phone, "555-1212") + + person = Person.objects.first() + person.address = Address(city="Londinium") + person.save() + + self.assertEqual(Person.objects.first().address.city, "Londinium") + + + person = Person.objects.first() + person["age"] = 35 + person.save() + self.assertEqual(Person.objects.first().age, 35) + if __name__ == '__main__': unittest.main()