欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Drf之单条数据的增删改查以及校验(五)

程序员文章站 2022-03-05 16:56:48
...

单条数据的增删改查

 # 前提:
# 1)序列化类中不能修改原字段的深度
# 2)通过 data=请求数据包 得到可以操作orm的序列化对象,instance来明确修改的对象,校验成功后还是走save()来更新
# 3)必须先校验,才能保存或更新

# 增
class Books(APIView):
    """
    {
        "name":"水浒传",
        "price":"88.88",
        "author":[1, 2, 3 ]
    }
    """
    def post(self, request):
        book_dic = request.data
        book_json = objson.BookJson(data=book_dic)
       	# 数据的校验
        if book_json.is_valid():
            book_json.save()  # 不涉及跨表操作
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': book_json.data
        })
# 查改删
class Book(APIView):
    def get(self, request, id):
        book_obj = models.Book.objects.filter(pk=id).first()
        book_data = objson.BookJson(book_obj).data
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': book_data
        })
    def put(self, request, id):
        book_obj = models.Book.objects.filter(pk=id).first()
        # instance来明确修改的对象,校验成功后还是走save()来保存
        book_json = objson.BookJson(data=request.data, instance=book_obj)
        if book_json.is_valid():
            book_json.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': book_json.data
        })
    def delete(self, request, id):
        models.Book.objects.filter(pk=id).delete()
        return Response({
            'status': 2,
            'msg': 'delete success',
        })

数据的校验

# views.py
class Books(APIView):
    def post(self, request):
        book_dic = request.data
        book_json = objson.BookJson(data=book_dic)
       	# 数据的校验
        if book_json.is_valid():
            # book_json.save()  # 不涉及跨表操作
            return Response({
                'status': 0,
                'msg': 'ok',
                'results': book_json.data
            })
        return Response({
            'status': 0,
            'msg': book_json.errors,
        })

    
# objson.py
class BookJson(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = '__all__'

    # 认证
    name = serializers.CharField(
        max_length=5,
        min_length=1,
        error_messages={
            "max_length": "太长了",
            "min_length": "太短了",
        }
    )

    # 局部钩子(validate_要校验的字段名)
    def validate_name(self, value):
        from rest_framework.exceptions import ValidationError
        if 'sb' in value:
            raise ValidationError("出现了敏感词汇")
        return value


    # def validate_price(self, value):
    #     from rest_framework.exceptions import ValidationError
    #     if float(value) < 0:
    #         raise ValidationError("价格不合理")
    #     return
    
    
    
# 了解:如果多个字段直接协同校验,采用全局钩子
def validate(self, attrs):
    from rest_framework.exceptions import ValidationError
    pwd = attrs.get('pwd')
    re_pwd = attrs.get('re_pwd')
    if pwd == re_pwd:
        return attrs
    else:
        raise ValidationError('密码校验失败')
相关标签: drf