Skip to main content
 首页 » 编程设计

python之在 Django 中使用事务

2024年11月01日45cyq1162

我在 python 3.7 上使用 django 1.11

在一个方法中,我想执行一些数据库查询,主要是更新对象之间的链接,我想使用这个方法来检查同步操作中需要更新的内容。下面是一个实现:

    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_test_only 参数的方法中,该参数应仅填充结果字典,而不进行随之而来的数据库更改。

所以这个方法可以用来做实际的工作,当sync_test_only为False时,也只报告要完成的工作,当sync_test_only 为 True

这就是 transaction.atomic() 的设计目的吗?这真的适用于我的用例吗?如果不是,实现此行为的更好方法是什么?

请您参考如下方法:

另一种选择是使用异常,例如 docs建议(阅读标题“您可能需要在回滚事务时手动恢复模型状态”下的部分):

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 

我建议创建一个自定义异常,这样您就不会意外捕获代码中其他地方引发的异常。