Skip to main content
 首页 » 编程设计

python之Django:事务原子性是否确保之后的代码发生在数据库保存之后

2024年11月01日26lyj

希望问题很清楚。我正在尝试在 model.save() 之后同步保存,但由于某些原因我不能使用 django 信号(所以请不要将其作为可能的解决方案提及)

我会:

def viewfunc(request): 
    # This code executes in autocommit mode (Django's default). 
    do_stuff() 
 
    with transaction.atomic(): 
        # This code executes inside a transaction. 
        do_more_stuff() 
    do_even_more_stuff() 

当我运行 do_even_more_stuff() 时,是否可以安全地假设使用 do_more_stuff() 完成的任何 model.save() 已保存到数据库中?

请您参考如下方法:

根据docs :

if the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

因此一般情况下的答案是否定的,但如果该 block 无一异常(exception)地完成,则可以安全地假设这一点。