菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
21
0

Avoid catching exceptions inside atomic! You may need to manually revert model state when rolling back a transaction. 避免异常程序不抛错误 回滚 导致 自增id不连续。

原创
05/13 14:22
阅读数 4812

 

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不连续。





发表评论

0/200
21 点赞
0 评论
收藏