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

标签 django django-orm

代码崩溃

@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/

相关文章:

python - 将 Django 脆皮表单与 FormView 混合

python - 覆盖抽象基类属性会影响其他子类吗?

python - 是否有用于查询嵌套 jsonfield 键的 django-orm 查找?

python - Django管理员使用Docker错误填充错误

python - 生成随机字母数字字符串作为模型的主键

python - 预取某些对象返回空值

django - 为什么编辑模型实例后无法保存它们?

django-orm - 我可以从Django ORM查询中删除ORDER BY吗?

Django 和 Django ORM : performance improvements to bulk updating records

python - Django ORM将当前公司注释给用户查询集