From 00430491caeaab6c2693dd437d5f0b25d7809fb4 Mon Sep 17 00:00:00 2001 From: Neurostack Date: Tue, 29 Mar 2016 11:46:03 -0600 Subject: [PATCH] Fixed bug accessing ListField (BaseList) with negative indices If you __setitem__ in BaseList with a negative index and then try to save this, you will get an error like: OperationError: Could not save document (cannot use the part (shape of signal.shape.-1) to traverse the element ({shape: [ 0 ]})). To fix this I rectify negative list indices in BaseList _mark_as_changed as the appropriate positive index. This fixes the above error. --- AUTHORS | 1 + docs/changelog.rst | 1 + mongoengine/base/datastructures.py | 3 ++- tests/fields/fields.py | 13 +++++++++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 758c52ea..758554c0 100644 --- a/AUTHORS +++ b/AUTHORS @@ -236,3 +236,4 @@ that much better: * Luo Peng (https://github.com/RussellLuo) * Bryan Bennett (https://github.com/bbenne10) * Gilb's Gilb's (https://github.com/gilbsgilbs) + * Joshua Nedrud (https://github.com/Neurostack) diff --git a/docs/changelog.rst b/docs/changelog.rst index 90de9556..3fa9eb74 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -11,6 +11,7 @@ Changes in 0.10.7 - DEV - count on ListField of EmbeddedDocumentField fails. #1187 - Fixed long fields stored as int32 in Python 3. #1253 - MapField now handles unicodes keys correctly. #1267 +- ListField now handles negative indicies correctly. #1270 Changes in 0.10.6 ================= diff --git a/mongoengine/base/datastructures.py b/mongoengine/base/datastructures.py index e4d2b392..ed6a46cc 100644 --- a/mongoengine/base/datastructures.py +++ b/mongoengine/base/datastructures.py @@ -199,7 +199,8 @@ class BaseList(list): def _mark_as_changed(self, key=None): if hasattr(self._instance, '_mark_as_changed'): if key: - self._instance._mark_as_changed('%s.%s' % (self._name, key)) + self._instance._mark_as_changed('%s.%s' % (self._name, + key % len(self))) else: self._instance._mark_as_changed(self._name) diff --git a/tests/fields/fields.py b/tests/fields/fields.py index 7575e8c6..b87c4366 100644 --- a/tests/fields/fields.py +++ b/tests/fields/fields.py @@ -1160,6 +1160,19 @@ class FieldTest(unittest.TestCase): simple = simple.reload() self.assertEqual(simple.widgets, [4]) + def test_list_field_with_negative_indices(self): + + class Simple(Document): + widgets = ListField() + + simple = Simple(widgets=[1, 2, 3, 4]).save() + simple.widgets[-1] = 5 + self.assertEqual(['widgets.3'], simple._changed_fields) + simple.save() + + simple = simple.reload() + self.assertEqual(simple.widgets, [1, 2, 3, 5]) + def test_list_field_complex(self): """Ensure that the list fields can handle the complex types."""