如何在基于Django类的视图中定义transaction.atomic?

时间:2014-11-27 14:15:03

标签: django

我希望基于类的视图中的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)
  1. 这是对的吗?
  2. 我可以只使post方法原子化吗?

2 个答案:

答案 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/