From 3569529a84837d42a680e13f64bc912be6d0937f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ericson?= Date: Sat, 8 Nov 2014 19:11:51 -0300 Subject: [PATCH] Fix KeyError on reload() from a DynamicDocument If the document is in memory and a field is deleted from the db, calling reload() would raise a KeyError. --- AUTHORS | 1 + mongoengine/document.py | 8 +++++++- tests/document/dynamic.py | 7 +++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 23930cc3..34f3d63f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -212,3 +212,4 @@ that much better: * Axel Haustant (https://github.com/noirbizarre) * David Czarnecki (https://github.com/czarneckid) * Vyacheslav Murashkin (https://github.com/a4tunado) + * André Ericson (https://github.com/aericson) diff --git a/mongoengine/document.py b/mongoengine/document.py index 2eab83ef..1891c164 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -543,7 +543,13 @@ class Document(BaseDocument): for field in self._fields_ordered: if not fields or field in fields: - setattr(self, field, self._reload(field, obj[field])) + try: + setattr(self, field, self._reload(field, obj[field])) + except KeyError: + # If field is removed from the database while the object + # is in memory, a reload would cause a KeyError + # i.e. obj.update(unset__field=1) followed by obj.reload() + delattr(self, field) self._changed_fields = obj._changed_fields self._created = False diff --git a/tests/document/dynamic.py b/tests/document/dynamic.py index a0bdb136..52136efc 100644 --- a/tests/document/dynamic.py +++ b/tests/document/dynamic.py @@ -81,6 +81,13 @@ class DynamicTest(unittest.TestCase): obj = collection.find_one() self.assertEqual(sorted(obj.keys()), ['_cls', '_id', 'name']) + def test_reload_after_unsetting(self): + p = self.Person() + p.misc = 22 + p.save() + p.update(unset__misc=1) + p.reload() + def test_dynamic_document_queries(self): """Ensure we can query dynamic fields""" p = self.Person()