当前位置 : 主页 > 网页制作 > HTTP/TCP >

drf中get/post/delete/put/patch五大接口

来源:互联网 收集:自由互联 发布时间:2021-06-16
五大接口总结 get 群查加单查 def get(self, request, *args, **kwargs): pk = kwargs.get('pk') if pk: many = False user_obj = models.Book.objects.filter(pk=pk, is_delete=False) else: many = True user_obj = models.Book.objects.filter(

五大接口总结

get

群查加单查

def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            many = False
            user_obj = models.Book.objects.filter(pk=pk, is_delete=False)
        else:
            many = True
            user_obj = models.Book.objects.filter(is_delete=False)
        if not user_obj:
            return Response({
                'status': 1,
                'msg': '请求资源不存在'
            })
        user_der = serializers.V2Bookserializers(instance=user_obj, many=many)
        return Ress(results=user_der).fanhui()

post

单增加群增

def post(self, request, *args, **kwargs):
        request_data = request.data
        # 单增
        if isinstance(request_data, dict):
            many = False
        # 群增
        elif isinstance(request_data, list):
            many = True
        else:
            raise exceptions.ValidationError('数据格式不正确')
        book_der = serializers.V2Bookserializers(data=request_data, many=many)
        book_der.is_valid(raise_exception=True)
        book_result = book_der.save()
        book_data = serializers.V2Bookserializers(instance=book_result, many=many).data
        return Ress(results=book_data).fanhui()

delete

def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            delete_obj = models.Book.objects.filter(pk=pk, is_delete=False).update(is_delete=True)

        else:
            pks = request.data.get('pks')
            delete_obj = models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True)
        if delete_obj:
            return Response({
                'status': 0,
                'msg': '删除成功'
            })
        return Response({
            'status': 1,
            'msg': '删除失败'
        })
注:

? 删除接口并不会走序列化,而且一般返回空

put

# 整体单改
    def put(self, request, *args, **kwargs):
        request_data = request.data
        pk = kwargs.get('pk')
        try:
            book_obj = models.Book.objects.filter(pk=pk, is_delete=False).first()
            if not book_obj:
                raise exceptions.ValidationError('xxx')
        except:
            return Response({
                'status': 1,
                'msg': '数据错误'
            })
        # 需要进行update时,要同时传入instance和data
        book_ser = serializers.V2Bookserializers(instance=book_obj, data=request_data)
        book_ser.is_valid(raise_exception=True)
        new_book_obj = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.V2Bookserializers(instance=new_book_obj).data
        })

patch

局部修改(单体和所有)

views.py

def patch(self, request, *args, **kwargs):
        # request_data = request.data
        # pk = kwargs.get('pk')
        # try:
        #     book_obj = models.Book.objects.filter(pk=pk, is_delete=False).first()
        #     if not book_obj:
        #         raise exceptions.ValidationError('xxx')
        # except:
        #     return Response({
        #         'status': 1,
        #         'msg': '数据错误'
        #     })
        # # partial默认为False,意为只要参加反序列化的字段,没有表明required为False的字段都是必填的
        # # partial为True,所有字段反序列化时都不是必填的
        # book_ser = serializers.V2Bookserializers(instance=book_obj, data=request_data, partial=True)
        # book_ser.is_valid(raise_exception=True)
        # new_book_obj = book_ser.save()
        # return Response({
        #     'status': 0,
        #     'msg': 'ok',
        #     'results': serializers.V2Bookserializers(instance=new_book_obj).data
        # })
        request_data = request.data
        pk = kwargs.get('pk')
        pks = []
        update_data = []
        if pk and isinstance(request_data, dict):
            pks = [pk, ]
            update_data = [request_data, ]
        elif not pk and isinstance(request_data, list):
            for dic in request_data:
                pks.append(dic.pop('pk'))
                update_data.append(dic)
        else:
            return Response({
                'status': 1,
                'msg': '数据格式错误'
            })
        if not pks or not update_data:
            return Response({
                'status': 1,
                'msg': '数据错误'
            })
        book_obj_list = []
        for i in pks:
            book_obj = models.Book.objects.filter(pk=i, is_delete=False).first()
            if not book_obj:
                return Response({
                    'status': 1,
                    'msg': '数据错误'
                })
            book_obj_list.append(book_obj)
        book_der = serializers.V2Bookserializers(instance=book_obj_list, data=update_data, many=True, partial=True)
        print(type(book_der))
        book_der.is_valid(raise_exception=True)
        new_objs = book_der.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.V2Bookserializers(instance=new_objs, many=True).data
        })

serializers.py中

首先群增群改都是由ListSerializer来完成的,但是ListSerializer提供了create方法,没有提供update方法,需要我们自己重写

class BookListSerializers(serializers.ListSerializer):
    def update(self, instance, validated_data):
        for index, obj in enumerate(instance):
            self.child.update(obj, validated_data[index])
        return instance
class V2Bookserializers(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'img', 'price', 'authors', 'publish', 'publish_name', 'get_author')
        ...
        list_serializer_class = BookListSerializers

我们要在序列化类中添加list_serializer_class = BookListSerializers不然走的还是ListSerializer

网友评论