我想正确处理在提交事务时可以引发IntegrityError异常,乍一看我看到实现它的两种选择,但不确定两者是否正确,有人可以澄清两者是否正确,为什么?
注意:我正在使用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)
答案 0 :(得分:0)
如果出现IntegrityError,请使用transaction.rollback()回滚整个事务。如果您只想回滚部分事务,请使用transaction.savepoint()。如果整个事务只有一个保存点,它将与transaction.rollback()具有相同的效果。