parent = Parent.objects.get(pk='something')
exceptions = []
with transaction.atomic():
for child in parent.children.all():
try:
# business logic which also saves other models
# I don't want this saved if there is an exception for any object in the loop
except Exception as e:
exceptions.append({
'id': child.id,
'error': str(e),
})
if len(exceptions) > 0:
transaction.set_rollback(True)
for exception in exceptions:
Child.objects.filter(pk=exception['id']) \
.update(error=exception['error']
# more business logic and raise exception
parent.is_blocked = True
parent.save()
# I don't want this exception to rollback all transactions
raise Exception('Parent {} is blocked'.format(parent.id))
我在上面的代码中遇到了一个错误。信息非常明确。我试图在块外回滚事务。
django.db.transaction.TransactionManagementError: 回滚标志在“原子”块之外不起作用。
有人找到了处理这种情况的方法吗?我希望我只是错过了一些简单的东西。如果您需要更多信息,请告诉我。