gpt4 book ai didi

django - select_for_update 开发 Django

转载 作者:行者123 更新时间:2023-12-04 11:39:37 30 4
gpt4 key购买 nike

Django documentation指出:

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().



这不再起作用的原因是自动提交是在数据库层而不是应用层完成的吗?以前的交易 would be held open until a data-altering function is called :

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 开始,在数据库层自动提交,一个 select_for_update后跟例如 write实际上会在两个事务中运行?如果是这种情况,那么没有 select_for_update变得无用,因为它的重点是 lock the rows until a data altering function was called ?

最佳答案

select_for_update只会在单个事务的上下文中锁定选定的行。如果你使用自动提交,它不会像你想象的那样做,因为每个查询实际上都是它自己的事务(包括 SELECT ... FOR UPDATE 查询)。将您的 View (或其他函数)包装在 transaction.atomic 中它会做你期望它做的事情。

关于django - select_for_update 开发 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17149587/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com