您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。