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.
This commit is contained in:
parent
3f3f93b0fa
commit
7913ed1841
@ -143,12 +143,14 @@ class Document(BaseDocument):
|
|||||||
|
|
||||||
doc = self.to_mongo()
|
doc = self.to_mongo()
|
||||||
|
|
||||||
created = '_id' not in doc
|
created = '_id' in doc
|
||||||
|
creation_mode = force_insert or not created
|
||||||
try:
|
try:
|
||||||
collection = self.__class__.objects._collection
|
collection = self.__class__.objects._collection
|
||||||
|
if creation_mode:
|
||||||
if force_insert:
|
if force_insert:
|
||||||
object_id = collection.insert(doc, safe=safe, **write_options)
|
object_id = collection.insert(doc, safe=safe, **write_options)
|
||||||
if created:
|
else:
|
||||||
object_id = collection.save(doc, safe=safe, **write_options)
|
object_id = collection.save(doc, safe=safe, **write_options)
|
||||||
else:
|
else:
|
||||||
object_id = doc['_id']
|
object_id = doc['_id']
|
||||||
@ -191,7 +193,7 @@ class Document(BaseDocument):
|
|||||||
reset_changed_fields(field, inspected_docs)
|
reset_changed_fields(field, inspected_docs)
|
||||||
|
|
||||||
reset_changed_fields(self)
|
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):
|
def update(self, **kwargs):
|
||||||
"""Performs an update on the :class:`~mongoengine.Document`
|
"""Performs an update on the :class:`~mongoengine.Document`
|
||||||
|
Loading…
x
Reference in New Issue
Block a user