gpt4 book ai didi

python - 当 'atomic' block 处于事件状态时,这是被禁止的。 Django 1.8

转载 作者:太空狗 更新时间:2023-10-30 01:13:56 27 4
gpt4 key购买 nike

我在安装 Django 1.8 时收到错误 This is forbidden when an 'atomic' block is active.

我已经尝试用 transaction.atomic(): 将其包装起来,并为 IntegrityError 创建异常

这是我的代码:

item = Item.objects.filter(item_id = data['item_id'])[:1][0]
iserializer = ItemSerializer(item, data=data, partial=True)
try:
with transaction.atomic():
if iserializer and iserializer.is_valid():
iserializer.save()
except IntegrityError:
pass

可能是什么原因造成的?为什么我的异常处理无法阻止收到此错误?

这是回溯:

Traceback (most recent call last):
File "<console>", line 4, in <module>
File "/home/vagrant/client/venv/bin/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 186, in save
self.instance = self.update(self.instance, validated_data)
File "/home/vagrant/client/venv/bin/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 880, in update
instance.save()
File "/vagrant/client/client/items/models.py", line 45, in save
transaction.commit()
File "/home/vagrant/client/venv/bin/local/lib/python2.7/site-packages/django/db/transaction.py", line 42, in commit
get_connection(using).commit()
File "/home/vagrant/client/venv/bin/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 172, in commit
self.validate_no_atomic_block()
File "/home/vagrant/client/venv/bin/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 322, in validate_no_atomic_block
"This is forbidden when an 'atomic' block is active.")
TransactionManagementError: This is forbidden when an 'atomic' block is active.

最佳答案

根据回溯,您似乎正在覆盖模型的 save() 方法并显式调用 transaction.commit()

File "/vagrant/client/client/items/models.py", line 45, in save
transaction.commit()

如错误所示,您不能在原子 block 内执行此操作,因为该 block 期望自己执行此操作。

更根本的是,这里的错误在于混合了高级事务 API (transaction.atomic()) 和低级事务 API (transaction.commit())。它们旨在作为彼此的替代品,而不是一起使用。

来自documentation :

Always prefer atomic() if possible at all. It accounts for the idiosyncrasies of each database and prevents invalid operations. The low level APIs are only useful if you’re implementing your own transaction management.

关于python - 当 'atomic' block 处于事件状态时,这是被禁止的。 Django 1.8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33760455/

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