From 7913ed1841abc7776b5efbb8362da3a76b1c35cf Mon Sep 17 00:00:00 2001 From: Slavi Pantaleev Date: Sat, 30 Jul 2011 00:52:37 +0300 Subject: [PATCH] Prevent double saving when doing a forced insert. When doing save(force_insert=True) on a document missing an _id field, the document was first getting inserted and then being saved a second time. Also refactatored the code a bit to make the intent (insert/update/delta-update) cleaner, especially since the `created` variable name was so confusing. --- mongoengine/document.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/mongoengine/document.py b/mongoengine/document.py index c41303d8..bd2bbda4 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -143,13 +143,15 @@ class Document(BaseDocument): doc = self.to_mongo() - created = '_id' not in doc + created = '_id' in doc + creation_mode = force_insert or not created try: collection = self.__class__.objects._collection - if force_insert: - object_id = collection.insert(doc, safe=safe, **write_options) - if created: - object_id = collection.save(doc, safe=safe, **write_options) + if creation_mode: + if force_insert: + object_id = collection.insert(doc, safe=safe, **write_options) + else: + object_id = collection.save(doc, safe=safe, **write_options) else: object_id = doc['_id'] updates, removals = self._delta() @@ -191,7 +193,7 @@ class Document(BaseDocument): reset_changed_fields(field, inspected_docs) reset_changed_fields(self) - signals.post_save.send(self.__class__, document=self, created=created) + signals.post_save.send(self.__class__, document=self, created=creation_mode) def update(self, **kwargs): """Performs an update on the :class:`~mongoengine.Document`