我希望基于类的视图中的post
方法是原子的。我已经定义了这个类:
class AcceptWith(View):
@method_decorator(login_required)
@method_decorator(user_passes_test(my_test))
@method_decorator(transaction.atomic)
def dispatch(self, *args, **kwargs):
return super(AcceptWith, self).dispatch(*args, **kwargs)
答案 0 :(得分:17)
假设您正在定义自己的方法来处理POST
,只需将transaction.atomic
装饰器直接应用于该方法。
class AcceptWith(View):
@transaction.atomic
def post(self, request, *args, **kwargs):
# your code here will be executed atomically
答案 1 :(得分:0)
我认为你不应该包装整个方法,也可能需要在回滚后执行自定义处理程序
def post(self, request, *args, **kwargs)
try:
with transaction.atomic():
pass # CRUD operations
except IntegrityError:
handle_exception() # this will run after rollback
https://docs.djangoproject.com/en/dev/topics/db/transactions/