Avoid catching exceptions inside atomic! You may need to manually revert model state when rolling b
Posted yuanjiangw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Avoid catching exceptions inside atomic! You may need to manually revert model state when rolling b相关的知识,希望对你有一定的参考价值。
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 b的主要内容,如果未能解决你的问题,请参考以下文章
如何处理异常? catch Exception OR catch Throwable
(Java)问题 Catch(IOException e) 和 catch(Exception e
catch (Exception e) catch (Throwable e) catch (IOException e) 再抛出异常,catch里的分别是啥意思