Django - Rollback save with transaction atomic

后端 未结 3 1867
猫巷女王i
猫巷女王i 2020-12-04 23:29

I am trying to create a view where I save an object but I\'d like to undo that save if some exception is raised. This is what I tried:

class MyView(         


        
3条回答
  •  粉色の甜心
    2020-12-05 00:06

    Atomicity Documentation

    To summarize, @transaction.atomic will execute a transaction on the database if your view produces a response without errors. Because you're catching the exception yourself, it appears to Django that your view executed just fine.

    If you catch the exception, you need to handle it yourself: Controlling Transactions

    If you need to produce a proper json response in the event of failure:

    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()
    

提交回复
热议问题