本文介绍了select_for_update 开发中的 Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 文档 声明:

如果您依靠自动事务"来提供锁定在 select_for_update() 和随后的写操作之间——一个极其脆弱的设计,但仍然有可能——你必须把atomic() 中的相关代码.

这不再起作用的原因是自动提交是在数据库层而不是应用层完成的吗?以前,事务将保持打开状态,直到调用数据更改函数:

Is the reason why this no longer works is that autocommit is done at the database layer and not the application layer? Previously the transaction would be held open until a data-altering function is called:

Django 的默认行为是运行一个打开的事务,当任何内置的数据更改模型时它会自动提交函数被调用

从 Django 1.6 开始,在数据库层自动提交,select_for_update 后跟例如 write 实际上会在两个事务中运行?如果是这种情况,那么 select_for_update 并没有变得无用,因为它的重点是 锁定行直到调用数据更改函数?

And since Django 1.6, with autcommit at the database layer, that a select_for_update followed by for example a write would actually run in two transactions? If this is the case, then hasn't select_for_update become useless as its point was to lock the rows until a data altering function was called?

推荐答案

select_for_update 将只锁定单个事务上下文中的选定行.如果您使用自动提交,它不会执行您认为的操作,因为每个查询实际上都是它自己的事务(包括 SELECT ... FOR UPDATE 查询).将您的视图(或其他函数)包装在 transaction.atomic 中,它会完全按照您的期望执行.

select_for_update will only lock the selected row within the context of a single transaction. If you're using autocommit, it won't do what you think it does, because each query will effectively be its own transaction (including the SELECT ... FOR UPDATE query). Wrap your view (or other function) in transaction.atomic and it'll do exactly what you're expecting it to do.

这篇关于select_for_update 开发中的 Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:11