rest_framework序列化组件校验

在views中

创新互联建站主营河源网站建设的网络公司,主营网站建设方案,手机APP定制开发,河源h5重庆小程序开发公司搭建,河源网站营销推广欢迎河源等地区企业咨询

from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import ViewSetMixin
from rest_framework.views import APIView
from rest_framework.response import Response
from app01 import Myser
from app01 import models
from app01.myutils.Myresponse import Responseone


class Book(ViewSetMixin,APIView):
    def get_book(self,request,*args,**kwargs):
        ret=models.Book.objects.all()
        ser=Myser.BookSer(instance=ret,many=True)
        return Response(ser.data)


    def set_book(self,request,*args,**kwargs):
        myres=Responseone()
        print(request.data)

        ser=Myser.BookSer(data=request.data)

        if ser.is_valid():
            ser.save()
            myres.msg='创建成功'
        else:
            myres.status=400
            myres.msg=ser.errors

        return Response(myres.get_dic)
    def change_book(self,request,pk,*args,**kwargs):
        print(pk)
        myres = Responseone()
        ret = models.Book.objects.all().filter(pk=pk).first()



        ser = Myser.BookSer(instance=ret,many=False,data=request.data)
        # 传instance和data是进行修改
        if ret:

            if ser.is_valid():

                ser.save()
                myres.msg = '修改成功'
            else:
                myres.status=401
                myres.msg = ser.errors
                print(ser.errors)





                print(Response(myres.get_dic))

        else:
            myres.msg='用户不存在'
            myres.status=403

        return Response(myres.get_dic)

        
        
        
在路由中

url(r'^book/(?P\d+)', views.Book.as_view({'get':'get_book','put':'change_book','post':'set_book'})),



在校验类中
校验的是前台传过来的数据


from rest_framework.exceptions import ValidationError
from app01 import models

from rest_framework import serializers

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

    name=serializers.CharField(max_length=4,min_length=2,required=True,error_messages={'max_length':'最长为4','min_length':'最短为2','required':'姓名必须填写'})
    
    
    
            # 局部钩子:
        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

文章标题:rest_framework序列化组件校验
文章源于:http://scyanting.com/article/ghhcso.html