django – 从原子块调用的“select_for_update”仍然是TransactionManagementError

我正在与
django合作开展一个大型项目.

我从一个模型的保存中调用一个芹菜任务,该模型调用一个在循环中调用另一个方法的方法.那是:

celery task --> function A()
A() --> for i in range(1,100): call function B()

现在B()包含一个atomic()装饰器,并在其中有一个select_for_update调用.

我仍然得到TransactionManagementError(‘select_for_update不能在事务之外使用.’)

我不知道为什么会这样.我已经测试了将任务延迟了几秒钟,以便在调用任务时提交保存.没有帮助.

我的问题是:当我已经在一个原子块内时,为什么我得到一个TransactionManagementError?

最佳答案 @ketanbhatt这可能会有所帮助

https://docs.djangoproject.com/en/1.9/ref/models/querysets/#select-for-update

Evaluating a queryset with select_for_update() in autocommit mode on backends which support SELECT … FOR UPDATE is a TransactionManagementError error because the rows are not locked in that case. If allowed, this would facilitate data corruption and could easily be caused by calling code that expects to be run in a transaction outside of one.

https://docs.djangoproject.com/en/1.9/topics/db/transactions/#managing-autocommit

Django will refuse to turn autocommit off when an atomic() block is active, because that would break atomicity.

点赞