gpt4 book ai didi

django - Django select_for_update不能在事务外部使用

转载 作者:行者123 更新时间:2023-12-04 02:37:49 31 4
gpt4 key购买 nike

我使用的是Django 1.5.1,并已升级到Django 1.6.6。

在Django 1.5.1中,我使用select进行更新以保证原子执行。

job_qs = Job.objects.select_for_update().filter(pk=job.id)
for job in job_qs:


不幸的是,这现在抛出一个错误:

  File "/srv/venvs/django-picdoc/local/lib/python2.7/site-packages/django/db/models/query.py", line 96, in __iter__
self._fetch_all()

File "/srv/venvs/django-picdoc/local/lib/python2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())

File "/srv/venvs/django-picdoc/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():

File "/srv/venvs/django-picdoc/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):

File "/srv/venvs/django-picdoc/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 776, in execute_sql
sql, params = self.as_sql()

File "/srv/venvs/django-picdoc/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 147, in as_sql
raise TransactionManagementError("select_for_update cannot be used outside of a transaction.")

TransactionManagementError: select_for_update cannot be used outside of a transaction.


有哪些解决方案可以解决此问题?

最佳答案

答案在错误中,将查询包装在事务中

Django的文档位于:https://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.atomic

一种方法是:

from django.db import transaction

def some_method():
with transaction.atomic():
job_qs = Job.objects.select_for_update().filter(pk=job.id)
for job in job_qs:

关于django - Django select_for_update不能在事务外部使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451087/

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