python – Django – 使用事务原子进行回滚保存
作者:互联网
我正在尝试创建一个保存对象的视图,但是如果引发一些异常,我想撤消该保存.这是我试过的:
class MyView(View):
@transation.atomic
def post(self, request, *args, **kwargs):
try:
some_object = SomeModel(...)
some_object.save()
if something:
raise exception.NotAcceptable()
# When the workflow comes into this condition, I think the previous save should be undome
# Whant am I missing?
except exception.NotAcceptable, e:
# do something
我究竟做错了什么?即使引发异常,some_object仍然在DataBase中.
解决方法:
总而言之,如果您的视图产生没有错误的响应,@ transaction.atomic将在数据库上执行事务.因为你自己正在捕获异常,所以Django认为你的视图执行得很好.
如果您发现异常,则需要自己处理:Controlling Transactions
如果您在发生故障时需要生成正确的json响应:
from django.db import SomeError, transaction
def viewfunc(request):
do_something()
try:
with transaction.atomic():
thing_that_might_fail()
except SomeError:
handle_exception()
render_response()
标签:python,atomicity,django,transactions,django-database 来源: https://codeday.me/bug/20190926/1822071.html