Do I need to explicitly use transactions with Djan

2019-01-20 05:08发布

According to http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations, in order to accept a nested serializer I need to create an update method. None of the examples use transactions although they do modify multiple rows/tables. Does the DRF somehow wrap things in transactions already, or should I explicitly put transaction.atomic() all over it?

Related PR:

3条回答
劫难
2楼-- · 2019-01-20 05:22

The related PR is unrelated to your question. PR is linked to the DRF specific exception handler that bypassed the default Django transaction scheme (https://github.com/tomchristie/django-rest-framework/pull/1204#issuecomment-52712621).

DRF doesn't specifically wrap things in a transaction to leave the users free to choose whatever they want to.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-20 05:31

first import transaction module from db, and then use the following

with transtaction.atomic():
    pass

This will ensure the atomicity and consistency of your data into database.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-20 05:35

You can also use Django's ATOMIC_REQUESTS database setting which will apply a transaction before the execution of each request and commit it if the request finishes successfully. More information here:

Database transactions - Tying transactions to HTTP requests

查看更多
登录 后发表回答