From d8d98b6143198b3c6cbe6f3aa4b5ad5bb099b1a3 Mon Sep 17 00:00:00 2001 From: Ollie Ford Date: Sat, 3 Dec 2016 21:10:05 +0000 Subject: [PATCH] Support Falsey `primary_key`s (#1354) --- mongoengine/document.py | 6 +++--- tests/document/instance.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/mongoengine/document.py b/mongoengine/document.py index 607b1bd9..91dcafc4 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -472,7 +472,7 @@ class Document(BaseDocument): Raises :class:`OperationError` if called on an object that has not yet been saved. """ - if not self.pk: + if self.pk is None: if kwargs.get('upsert', False): query = self.to_mongo() if "_cls" in query: @@ -604,7 +604,7 @@ class Document(BaseDocument): elif "max_depth" in kwargs: max_depth = kwargs["max_depth"] - if not self.pk: + if self.pk is None: raise self.DoesNotExist("Document does not exist") obj = self._qs.read_preference(ReadPreference.PRIMARY).filter( **self._object_key).only(*fields).limit( @@ -655,7 +655,7 @@ class Document(BaseDocument): def to_dbref(self): """Returns an instance of :class:`~bson.dbref.DBRef` useful in `__raw__` queries.""" - if not self.pk: + if self.pk is None: msg = "Only saved documents can have a valid dbref" raise OperationError(msg) return DBRef(self.__class__._get_collection_name(), self.pk) diff --git a/tests/document/instance.py b/tests/document/instance.py index cb2c1746..1342f981 100644 --- a/tests/document/instance.py +++ b/tests/document/instance.py @@ -3202,5 +3202,20 @@ class InstanceTest(unittest.TestCase): self.assertEqual(b._instance, a) self.assertEqual(idx, 2) + def test_falsey_pk(self): + """Ensure that we can create and update a document with Falsey PK. + """ + class Person(Document): + age = IntField(primary_key=True) + height = FloatField() + + person = Person() + person.age = 0 + person.height = 1.89 + person.save() + + person.update(set__height=2.0) + + if __name__ == '__main__': unittest.main()