序列化组件之数据校验与保存

一  序列化组件之请求数据校验和保存功能

组件

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = '__all__'

    name = serializers.CharField(min_length=2, error_messages={'required': '该字段必填'})
    authors = serializers.CharField(required=False)

views

class Books(APIView):
    def get(self, request, *args, **kwargs):
        ret = models.Book.objects.all()
        # 生成一个序列化的对象,传参数
        # 序列化多条,记住many=True
        book_ser = BookSerializer(ret, many=True, context={'request': request})
        print(book_ser.data)
        return JsonResponse(book_ser.data, safe=False)

    def post(self, request, *args, **kwargs):
        # 前端传递过来的数据从data中取
        # 用序列化类的数据校验
        # data参数,是要校验的数据
        response = {'status': 100, 'msg': '成功'}
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            # 如果数据校验通过,is_valid是True
            # 保存到数据库,ser是谁的对象?继承了ModelSerializer的类的对象
            ser.save()
        else:
            response['status'] = 101
            response['msg'] = ser.errors
        return JsonResponse(response, safe=False)

 局部钩子与全局钩子

# 局部钩子:
    def validate_name(self, value):
        # print(value)
        if value.startswith('sb'):
            # 不能以sb开头
            raise ValidationError('不能以sb开头')
        else:
            return value

    # 全局钩子找到了
    def validate(self, value):
        # value是所有校验通过数据的字典
        print(value)
        name = value.get('name')
        price = value.get('price')
        if name and price:
            if str(name) == str(price):
                return value
            else:
                raise ValidationError('名字跟价格不相等')
        return value

全局钩子与局部钩子校验

class BookDetail(APIView):
    def get(self,request,pk):
        response={'status':100,'msg':'成功'}
        ret = models.Book.objects.filter(nid=pk).first()
        if ret:
            book_ser = BooksSerializer(ret,many=False)
            response['data']=book_ser.data
        else:
            response['status']=101
            response['msg']='您查询的对象不存在'

        return JsonResponse(response,safe=False)

    def put(self,request,pk):
        response={'status':100,'msg':'成功'}
        ret = models.Book.objects.all().filter(pk=pk).first()
        if ret:
            ret_ser = BooksSerializer(data=request.data,instance=ret)
            if ret_ser.is_valid():
                ret_ser.save()
            else:
                response['status']=101
                response['msg']=ret_ser.errors
        else:
            response['status']=102
            response['msg']='您访问的对象不存在'
        return JsonResponse(response,safe=False)

 

前台错误数据

 钩子校验

 

posted @ 2018-12-12 17:43  zhaijihai  阅读(441)  评论(0编辑  收藏  举报