1.验证数据的自定义类
class BooksDRFt(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' #要验证的字段 author = serializers.CharField(required=False) #要验证的字段 name = serializers.CharField(min_length=2, error_messages{'required': '不能为空', 'min_length': '最短长度是二'}) #局部钩子 def validate_name(self,value): response = {'status':100,'msg':'成功'} res = models.Book.objects.filter(name=value) if res: raise exceptions.ValidationError('书名重复!') else: return value #全局钩子 def validate(self, attrs): name = attrs.get('name') price = attrs.get('price') if str(name) == str(int(price)): raise exceptions.ValidationError('重复!') else: return attrs
注意:1 必须继承ModelSerializer
2.在视图函数中的使用
1 验证+存储数据
class Books(APIView): def post(self,request): book_res = common.BooksDRFt(data=request.data) if book_res.is_valid(): book_res.save() return JsonResponse(book_res.data,safe=False) else: return JsonResponse(book_res.errors)
2 验证+修改数据
class BooksUpdateCreate(APIView): def put(self,request,id): book = models.Book.objects.filter(id=id).first() book_res = common.BooksDRFt(data=request.data,instance=book) if book_res.is_valid(): book_res.save() return JsonResponse(book_res.data,safe=False) else: return JsonResponse(book_res.errors)