from rest_framework.response import Response from rest_framework.views import APIView
from api import models, serializers from utils.response import APIResponse
class BookV2(APIView): def patch(self, request, *args, **kwargs): request_data = request.data pk = kwargs.get('pk') if pk and isinstance(request_data, dict): pks = [pk] request_data = [request_data] elif not pk and isinstance(request_data, list): pks = [] for dic in request_data: pk = dic.pop('pk', None) if pk: pks.append(pk) else: return APIResponse(1, 'list data error') else: return APIResponse(2, 'data error') pks_objs = [] new_request_data = [] for index, pk in enumerate(pks): try: obj = models.Book.objects.get(pk=pk, is_delete=False) pks_objs.append(obj) new_request_data.append(request_data[index]) except: continue
book_ser = serializers.BookV2ModelSerializer(instance=pks_objs, data=new_request_data, partial=True, many=True) book_ser.is_valid(raise_exception=True) book_objs = book_ser.save()
book_objs_data = serializers.BookV2ModelSerializer(book_objs, many=True).data return APIResponse(results=book_objs_data, http_status=201, token=from rest_framework.response import Response from rest_framework.views import APIView
from api import models, serializers from utils.response import APIResponse
class BookV2(APIView): def patch(self, request, *args, **kwargs): request_data = request.data pk = kwargs.get('pk') if pk and isinstance(request_data, dict): pks = [pk] request_data = [request_data] elif not pk and isinstance(request_data, list): pks = [] for dic in request_data: pk = dic.pop('pk', None) if pk: pks.append(pk) else: return APIResponse(1, 'list data error') else: return APIResponse(2, 'data error') pks_objs = [] new_request_data = [] for index, pk in enumerate(pks): try: obj = models.Book.objects.get(pk=pk, is_delete=False) pks_objs.append(obj) new_request_data.append(request_data[index]) except: continue
book_ser = serializers.BookV2ModelSerializer(instance=pks_objs, data=new_request_data, partial=True, many=True) book_ser.is_valid(raise_exception=True) book_objs = book_ser.save()
book_objs_data = serializers.BookV2ModelSerializer(book_objs, many=True).data return APIResponse(results=book_objs_data, http_status=201, token="mytoken")
|