Jesvin Jose
Jesvin Jose

Reputation: 23088

How to define transaction.atomic in a Django class-based view?

I want the post method in the class-based view to be atomic. I have defined the class so:

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. Is this correct?
  2. Can I make only the post method atomic?

Upvotes: 9

Views: 8320

Answers (2)

madzohan
madzohan

Reputation: 11808

I think you should not wrap whole method, also you may want custom handler execute after rollback

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/

Upvotes: 1

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

Assuming that you're defining your own method to handle the POST, just apply the transaction.atomic decorator directly to that method.

class AcceptWith(View):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        # your code here will be executed atomically

Upvotes: 24

Related Questions