Skip to content

Can not update documents with type of pk=int and value 0 #1352

@michal-szostak

Description

@michal-szostak

Documents with pk type defined as fields.IntField(primary_key=True) fail to be updated giving following error:

Traceback (most recent call last):
  File "mongoengine_bug.py", line 12, in <module>
    doc.update(set__field='changed field')
  File "/usr/local/lib/python2.7/site-packages/mongoengine/document.py", line 474, in update
    'attempt to update a document not yet saved')
mongoengine.errors.OperationError: attempt to update a document not yet saved

Here is a self contained code which can reproduce this bug:

import mongoengine

mongoengine.connect('test_db')

class TestDocument(mongoengine.Document):
    id = mongoengine.fields.IntField(primary_key=True)
    field = mongoengine.fields.StringField()

doc = TestDocument(id=0, field='')
doc.save()

doc.update(set__field='changed field')

It seems that mongoengine/document.py line 466 is at fault:

 if not self.pk:

So if Document's id is 0 it is evaluated to false and throws exception
I think it should be changed to:

if self.pk is None:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions