Can an instance be committed if an exception occurs in the post_save handler?

I have a post_save handler that inserts additional records into the database, referencing the newly created or updated instance. However, an error may occur when inserting additional records (possibly a violation of the restriction).

If an post_save is thrown in the post_save handler, is it possible that the original instance will be committed?

The answer may depend on these questions:

  • Does Django auto-commit before or after the post_save signal?
  • Is Django trying to use nested transactions to rollback an instance that is saved when an error occurs in post_save ?
+4
source share
1 answer

According to the docs, if you use autocommit , the changes in the original instance will be committed to .save() before any post_save signal post_save . An exception in post_save does not post_save changes to the original instance.

You can confirm this by looking at the source on save_base in django/db/models/base.py Auto-reporting will occur on line 555 (in 1.4.2), but the post_save signal post_save not sent until line 564 . You can also see that Django is not trying to use nested transactions in .save() .

If you use django.middleware.transaction.TransactionMiddleware and did not override its behavior using the autocommit decorator, an exception during post_save throw the whole transaction, including changes to the original instance.

+5
source

Source: https://habr.com/ru/post/1447778/


All Articles