diff --git a/apps/utils/mixins.py b/apps/utils/mixins.py index dff0fd27..94703573 100755 --- a/apps/utils/mixins.py +++ b/apps/utils/mixins.py @@ -18,6 +18,7 @@ from apps.utils.serializers import PkSerializer from rest_framework.decorators import action from apps.utils.serializers import ComplexSerializer from django.db.models import F +from django.db import transaction # 实例化myLogger myLogger = logging.getLogger('log') @@ -80,7 +81,8 @@ class BulkCreateModelMixin(CreateModelMixin): def after_bulk_create(self, objs): pass - + + @transaction.atomic def create(self, request, *args, **kwargs): """创建(支持批量) @@ -103,6 +105,7 @@ class BulkUpdateModelMixin(UpdateModelMixin): def after_bulk_update(self, objs): pass + @transaction.atomic def partial_update(self, request, *args, **kwargs): """部分更新(支持批量) @@ -111,6 +114,7 @@ class BulkUpdateModelMixin(UpdateModelMixin): kwargs['partial'] = True return self.update(request, *args, **kwargs) + @transaction.atomic def update(self, request, *args, **kwargs): """更新(支持批量) @@ -145,6 +149,7 @@ class BulkUpdateModelMixin(UpdateModelMixin): class BulkDestroyModelMixin(DestroyModelMixin): @swagger_auto_schema(request_body=PkSerializer) + @transaction.atomic def destroy(self, request, *args, **kwargs): """删除(支持批量) diff --git a/apps/utils/viewsets.py b/apps/utils/viewsets.py index ad6de925..41588d26 100755 --- a/apps/utils/viewsets.py +++ b/apps/utils/viewsets.py @@ -20,12 +20,6 @@ from drf_yasg.utils import swagger_auto_schema import json from django.db import connection from django.core.exceptions import ObjectDoesNotExist -from django.db import transaction - -def enable_transaction(func): - """装饰器 标记这个action需要事务""" - func._enable_transaction = True - return func class CustomGenericViewSet(MyLoggingMixin, GenericViewSet): """ @@ -66,26 +60,6 @@ class CustomGenericViewSet(MyLoggingMixin, GenericViewSet): cls._initialized = True return super().__new__(cls) - def dispatch(self, request, *args, **kwargs): - # 判断是否需要事务 - if self._should_use_transaction(request): - with transaction.atomic(): - return super().dispatch(request, *args, **kwargs) - else: - return super().dispatch(request, *args, **kwargs) - - def _should_use_transaction(self, request): - """判断当前请求是否需要事务""" - # 1. 标准写操作需要事务 - if self.action in ['create', 'update', 'partial_update', 'destroy']: - return True - action_method = getattr(self, self.action, None) - if not action_method: - return False - elif hasattr(action_method, '_enable_transaction'): - return True - return False - def finalize_response(self, request, response, *args, **kwargs): # 如果是流式响应,直接返回 if isinstance(response, StreamingHttpResponse):