I want to handle properly an IntegrityError exception can be raised when a transaction is commited, and at first glance i see two alternatives to implement that, but not sure if both are correct, Can somebody clarify if both are right or not, and why?
Note: I’m using PostgreSQL
# alternative one
try:
with transaction.commit_on_success():
# db operation 1
# db operation 2
except IntegrityError:
transaction.rollback()
#alternative two
with transaction.commit_manually():
sid = transaction.savepoint()
# db operation 1
# db operation 2
try:
transaction.savepoint_commit(sid)
except IntegrityError:
transaction.savepoint_rollback(sid)
In the event of an IntegrityError, use transaction.rollback() to roll back the entire transaction. If you only want to roll back parts of the transaction use transaction.savepoint(). If you only have one savepoint for the entire transaction, it will have the same effect as transaction.rollback().