校验功能的三种方式
Ⅰ 字段自己的校验规格(max_length...)
略....
Ⅱ validators的校验
urls.py路由
from django.contrib import admin
from django.urls import path,re_path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('books', views.Books.as_view()),
]
serializers.py自定义序列化器
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from app01 import models
def check(data): # validators字段校验
if len(data) > 10:
raise ValidationError('你太长了')
else:
return data
# 序列化器类(序列化Book表)
class BookSerializer(serializers.Serializer):
# 需要序列化的字段
id = serializers.IntegerField(required=False) # required设置后表示改字段可以不传
title = serializers.CharField(max_length=32, min_length=2)
price = serializers.DecimalField(max_digits=6, decimal_places=2)
publish = serializers.CharField(max_length=32, validators=[check, ]) # validators传列表,会
执行列表的函数进行字段校验
def create(self, validated_data): # 调用Serializer必须重写create方法
res = models.Book.objects.create(**validated_data)
return res
views.py视图函数
from django.shortcuts import render
from rest_framework.views import APIView
from django.views import View
from rest_framework.request import Request
from rest_framework.response import Response
from app01 import models
# Create your views here.
from app01.serializer import BookSerializer
class Books(APIView):
def get(self,request,*args,**kwargs):
res = models.Book.objects.all()
# 借助于序列化器
ser = BookSerializer(instance=res,many=True)
return Response(ser.data)
def post(self,request):
res = request.data # post提交的是数据都在这里,是一个字典
ser = BookSerializer(data=res) # 这里针对数据往哪个表存识别不了,所以在序列化类里需要重写create方法
if ser.is_valid():
ser.save() # 调用save保存到数据库
return Response(ser.data)
else:
return Response(ser.errors)
Ⅲ 反序列换的局部钩子和全局钩子
serializers.py自定义序列化器
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from app01 import models
class BookSerializer(serializers.Serializer):
# 需要序列化的字段
id = serializers.IntegerField(required=False) # required设置后表示改字段可以不传
title = serializers.CharField(max_length=32, min_length=2)
price = serializers.DecimalField(max_digits=6, decimal_places=2)
publish = serializers.CharField(max_length=32, validators=[check, ])
def create(self, validated_data): # 调用Serializer必须重写create方法
res = models.Book.objects.create(**validated_data)
return res
def validate_title(self, data): # 局部钩子,带一个data,data就是改字段的数据
if data.startswith('sb'):
raise ValidationError('不能以sb开头')
else:
return data
def validate(self, attrs): # 全局钩子,attrs是全部的数据
title = attrs.get('title')
publish = attrs.get('publish')
if title == publish:
raise ValidationError('书名不能同出版社相同')
else:
return attrs
views.py视图函数 -- 不变