Django开发中的select_for_update [英] select_for_update in development Django
问题描述
Django文档指出:
如果您依靠自动交易"来提供锁定 在select_for_update()和随后的写操作之间 极其脆弱的设计,但仍然有可能-您必须将 atomic()中的相关代码.
If you were relying on "automatic transactions" to provide locking between select_for_update() and a subsequent write operation — an extremely fragile design, but nonetheless possible — you must wrap the relevant code in 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’s default behavior is to run with an open transaction which it commits automatically when any built-in, data-altering model function is called
从Django 1.6开始,在数据库层具有autcommit,那么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.
这篇关于Django开发中的select_for_update的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!