Skip to content

Commit dcf3edb

Browse files
authored
Merge pull request #2094 from divomen/negative_indexes_in_list
Supported updates of an array by negative index
2 parents 1170de1 + c85b59d commit dcf3edb

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

mongoengine/base/datastructures.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ def __init__(self, list_items, instance, name):
120120
super(BaseList, self).__init__(list_items)
121121

122122
def __getitem__(self, key):
123+
# change index to positive value because MongoDB does not support negative one
124+
if isinstance(key, int) and key < 0:
125+
key = len(self) + key
123126
value = super(BaseList, self).__getitem__(key)
124127

125128
if isinstance(key, slice):

tests/document/test_instance.py

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), "../fields/mongoengine.png")
4242

4343

44-
class TestInstance(MongoDBTestCase):
44+
class TestDocumentInstance(MongoDBTestCase):
4545
def setUp(self):
4646
class Job(EmbeddedDocument):
4747
name = StringField()
@@ -3617,6 +3617,51 @@ class A(Document):
36173617
assert b._instance == a
36183618
assert idx == 2
36193619

3620+
def test_updating_listfield_manipulate_list(self):
3621+
class Company(Document):
3622+
name = StringField()
3623+
employees = ListField(field=DictField())
3624+
3625+
Company.drop_collection()
3626+
3627+
comp = Company(name="BigBank", employees=[{"name": "John"}])
3628+
comp.save()
3629+
comp.employees.append({"name": "Bill"})
3630+
comp.save()
3631+
3632+
stored_comp = get_as_pymongo(comp)
3633+
self.assertEqual(
3634+
stored_comp,
3635+
{
3636+
"_id": comp.id,
3637+
"employees": [{"name": "John"}, {"name": "Bill"}],
3638+
"name": "BigBank",
3639+
},
3640+
)
3641+
3642+
comp = comp.reload()
3643+
comp.employees[0]["color"] = "red"
3644+
comp.employees[-1]["color"] = "blue"
3645+
comp.employees[-1].update({"size": "xl"})
3646+
comp.save()
3647+
3648+
assert len(comp.employees) == 2
3649+
assert comp.employees[0] == {"name": "John", "color": "red"}
3650+
assert comp.employees[1] == {"name": "Bill", "size": "xl", "color": "blue"}
3651+
3652+
stored_comp = get_as_pymongo(comp)
3653+
self.assertEqual(
3654+
stored_comp,
3655+
{
3656+
"_id": comp.id,
3657+
"employees": [
3658+
{"name": "John", "color": "red"},
3659+
{"size": "xl", "color": "blue", "name": "Bill"},
3660+
],
3661+
"name": "BigBank",
3662+
},
3663+
)
3664+
36203665
def test_falsey_pk(self):
36213666
"""Ensure that we can create and update a document with Falsey PK."""
36223667

0 commit comments

Comments
 (0)