1. 程式人生 > >rest_framework序列化元件校驗

rest_framework序列化元件校驗

在views中

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<pk>\d+)', views.Book.as_view({'get':'get_book','put':'change_book','post':'set_book'})),



在校驗類中




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':'姓名必須填寫'})