gpt4 book ai didi

django - “select_for_update” 在原子 block 内调用仍然 TransactionManagementError

转载 作者:行者123 更新时间:2023-12-05 00:39:53 24 4
gpt4 key购买 nike

代码崩溃

@transaction.atomic
def cancel_one(o_id):
order= Order.objects.select_for_update().get(id=o_id)

加注

TransactionManagementError('select_for_update cannot be used outside of a transaction.')

django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction.

我已通过 transaction.get_connection().in_atomic_block 检查了我的代码是否在事务中。

它出现在交易中,但仍然引发

Error: django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction.

我的代码:

# Step1
def cancel_one(o_id):
print("DO")
cxn = transaction.get_connection()
if cxn.in_atomic_block:
print("We're inside a transaction!")
order= Order.objects.select_for_update().get(id=o_id)

# Step2
@transaction.atomic
def cancel_one(o_id):
print("DO")
cxn = transaction.get_connection()
if cxn.in_atomic_block:
print("We're inside a transaction!")
order= Order.objects.select_for_update().get(id=o_id)

代码结果

# Step1
-----------------------
DO
-----------------------

# Step2
-----------------------
DO
"We're inside a transaction!"
-----------------------

最佳答案

您是否有机会使用 DBRouters?我遇到了麻烦-技巧是在事务和 select_for_update 上定义数据库

with transaction.atomic(using='db_x'):
order = Order.objects.using('db_x').select_for_update().get(id=o_id)

关于django - “select_for_update” 在原子 block 内调用仍然 TransactionManagementError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466408/

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