Python 在Django中使用事务
我正在Python3.7上使用django 1.11 在一个方法中,我想执行一些数据库查询,主要是更新对象之间的链接,我想使用这个方法对同步操作中需要更新的内容执行检查。以下是一个实施方案:Python 在Django中使用事务,python,django,atomicity,Python,Django,Atomicity,我正在Python3.7上使用django 1.11 在一个方法中,我想执行一些数据库查询,主要是更新对象之间的链接,我想使用这个方法对同步操作中需要更新的内容执行检查。以下是一个实施方案: results = {} with transaction.atomic(): sid = transaction.savepoint() for speaker_user in speaker_users: # here my co
results = {}
with transaction.atomic():
sid = transaction.savepoint()
for speaker_user in speaker_users:
# here my code checks all sorts of things, updates the database with
# new connections between objects and stores them all in the
# results-dict, using a lot of code in other classes which
# I really dont want to change for this operation
if sync_test_only:
transaction.savepoint_rollback(sid)
else:
transaction.savepoint_commit(sid)
return results
此代码段用于带有sync\u test\u only
参数的方法中,该参数应仅填充结果dict,而不进行随之进行的数据库更改
因此,当sync\u test\u only
为False
时,此方法可用于执行实际工作,当sync\u test\u only
为True
时,此方法也仅报告要执行的工作
这就是
transaction.atomic()
的设计目的吗?这在我的用例中真的有效吗?如果没有,实现此行为的更好方法是什么?另一种选择是使用异常,如建议(阅读标题“回滚事务时可能需要手动还原模型状态”下的部分):
我建议创建一个自定义异常,这样您就不会意外地捕获代码中其他地方出现的异常。您是否尝试过它,以了解它是否有效?
class MyException(Exception):
pass
def f(do_commit=False):
results = {}
try:
with transaction.atomic():
for speaker_user in speaker_users:
pass
if not do_commit:
raise MyException
except MyException:
# do nothing here
pass
return results