码迷,mamicode.com
首页 > 其他好文 > 详细

Avoid catching exceptions inside atomic! You may need to manually revert model state when rolling back a transaction.

时间:2020-04-26 01:15:33      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:情况   ted   pen   origin   django   manual   not   fir   写法   

 

https://docs.djangoproject.com/en/3.0/topics/db/transactions/

 

You may need to manually revert model state when rolling back a transaction.

The values of a model’s fields won’t be reverted when a transaction rollback happens. This could lead to an inconsistent model state unless you manually restore the original field values.

For example, given MyModel with an active field, this snippet ensures that the ifobj.active check at the end uses the correct value if updating active to True fails in the transaction:

from django.db import DatabaseError, transaction

obj = MyModel(active=False)
obj.active = True
try:
    with transaction.atomic():
        obj.save()
except DatabaseError:
    obj.active = False

if obj.active:
    ...




id 不连续




User.objects.get(x=y)注意这种写法 当且仅当需要x=y的情况下才不会抛异常 exception ;raise ParamError(CustomerError.X_NOT_EXIST)
可以使得事务回滚;但是 不raise error 不会使得事务回滚。


回滚 导致 自增id不连续。





Avoid catching exceptions inside atomic! You may need to manually revert model state when rolling back a transaction.

标签:情况   ted   pen   origin   django   manual   not   fir   写法   

原文地址:https://www.cnblogs.com/yuanjiangw/p/12776499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!