diff --git a/mongoengine/document.py b/mongoengine/document.py index 6ccda997..c41303d8 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -193,6 +193,18 @@ class Document(BaseDocument): reset_changed_fields(self) signals.post_save.send(self.__class__, document=self, created=created) + def update(self, **kwargs): + """Performs an update on the :class:`~mongoengine.Document` + A convenience wrapper to :meth:`~mongoengine.QuerySet.update`. + + Raises :class:`OperationError` if called on an object that has not yet + been saved. + """ + if not self.pk: + raise OperationError('attempt to update a document not yet saved') + + return self.__class__.objects(pk=self.pk).update_one(**kwargs) + def delete(self, safe=False): """Delete the :class:`~mongoengine.Document` from the database. This will only take effect if the document has been previously saved. diff --git a/tests/document.py b/tests/document.py index 92aa3c2e..e1c536e5 100644 --- a/tests/document.py +++ b/tests/document.py @@ -1203,6 +1203,29 @@ class DocumentTest(unittest.TestCase): self.assertEqual(person.name, None) self.assertEqual(person.age, None) + def test_document_update(self): + + def update_not_saved_raises(): + person = self.Person(name='dcrosta') + person.update(set__name='Dan Crosta') + + self.assertRaises(OperationError, update_not_saved_raises) + + author = self.Person(name='dcrosta') + author.save() + + author.update(set__name='Dan Crosta') + author.reload() + + p1 = self.Person.objects.first() + self.assertEquals(p1.name, author.name) + + def update_no_value_raises(): + person = self.Person.objects.first() + person.update() + + self.assertRaises(OperationError, update_no_value_raises) + def test_embedded_update(self): """ Test update on `EmbeddedDocumentField` fields diff --git a/tests/queryset.py b/tests/queryset.py index a07ff927..51c95112 100644 --- a/tests/queryset.py +++ b/tests/queryset.py @@ -242,7 +242,7 @@ class QuerySetTest(unittest.TestCase): self.Person.objects(pk=author.pk).update({}) def update_one_raises(): - self.Person.objects(pk=author.pk).update({}) + self.Person.objects(pk=author.pk).update_one({}) self.assertRaises(OperationError, update_raises) self.assertRaises(OperationError, update_one_raises)