您好,登錄后才能下訂單哦!
在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 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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。