新功能: 加入批量新增和批量修改

pull/79/head
猿小天 2022-11-16 23:31:10 +08:00
parent c38efecd79
commit 9b56c7964b
1 changed files with 13 additions and 3 deletions

View File

@ -8,6 +8,7 @@
"""
import uuid
from django.db import transaction
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action
@ -50,6 +51,7 @@ class CustomModelViewSet(ModelViewSet,ImportSerializerMixin,ExportSerializerMixi
return self.values_queryset
return super().get_queryset()
def get_serializer_class(self):
action_serializer_name = f"{self.action}_serializer_class"
action_serializer_class = getattr(self, action_serializer_name, None)
@ -57,6 +59,16 @@ class CustomModelViewSet(ModelViewSet,ImportSerializerMixin,ExportSerializerMixi
return action_serializer_class
return super().get_serializer_class()
# 通过many=True直接改造原有的API使其可以批量创建
def get_serializer(self, *args, **kwargs):
serializer_class = self.get_serializer_class()
kwargs.setdefault('context', self.get_serializer_context())
if isinstance(self.request.data, list):
with transaction.atomic():
return serializer_class(many=True, *args, **kwargs)
else:
return serializer_class(*args, **kwargs)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data, request=request)
serializer.is_valid(raise_exception=True)
@ -92,9 +104,7 @@ class CustomModelViewSet(ModelViewSet,ImportSerializerMixin,ExportSerializerMixi
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
request_data = request.data
soft_delete = request_data.get('soft_delete',True)
instance.delete(soft_delete=soft_delete)
instance.delete()
return DetailResponse(data=[], msg="删除成功")