django - transaction
Posted 在路上的少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django - transaction相关的知识,希望对你有一定的参考价值。
1 def user_atomic(): 2 User.objects.create(name=\'purk1\', email=\'pwu1@maxprocessing.com\') 3 4 User.objects.create(user_id=\'purk2\', name=\'purk2\', email=\'pwu2@maxprocessing.com\') 5 6 User.objects.create(name=\'purk3\', email=\'pwu3@maxprocessing.com\') 7 8 9 @transaction.atomic 10 def user_atomic_decorator(): 11 User.objects.create(name=\'purk1\', email=\'pwu1@maxprocessing.com\') 12 13 User.objects.create(user_id=\'purk2\', name=\'purk2\', email=\'pwu2@maxprocessing.com\') 14 15 User.objects.create(name=\'purk3\', email=\'pwu3@maxprocessing.com\') 16 17 18 @transaction.atomic 19 def user_atomic_decorator_1(): 20 User.objects.create(name=\'purk1\', email=\'pwu1@maxprocessing.com\') 21 22 try: 23 with transaction.atomic(): 24 User.objects.create(user_id=\'purk2\', name=\'purk2\', email=\'pwu2@maxprocessing.com\') 25 except Exception as e: 26 e 27 User.objects.create(name=\'purk3\', email=\'pwu3@maxprocessing.com\') 28 29 @transaction.atomic 30 def user_atomic_decorator_except(): 31 User.objects.create(name=\'purk1\', email=\'pwu1@maxprocessing.com\') 32 try: 33 User.objects.create(user_id=\'purk2\', name=\'purk2\', email=\'pwu2@maxprocessing.com\') 34 except Exception as e: 35 e 36 User.objects.create(name=\'purk3\', email=\'pwu3@maxprocessing.com\')
user_id 为uuid类型,所以user_id=\'purk2\'肯定会出错,
result:
在atomic中错误的使用try except则会抛出TransactionManagementError的异常,同时transaction失效了,没有正常回滚。
用atomic装饰之后,里面的结果就被回滚了,但是用try except包裹的atomic不会影响外层的transaction回滚
以上是关于django - transaction的主要内容,如果未能解决你的问题,请参考以下文章