is_valid(raise_exception=True) # 校验是否有异常 如果有就抛出异常 然后代码运行到此为止 serializer.save() return Response({'code': 200, 'msg': 'ok'}) serializer.py from rest_framework import serializers from app01.models import Student from rest_framework.exceptions import ValidationError class ...
只要执行序列化类对象的.is_valid就会执行 BaseSerializer的is_valid---》就会执行:self._validated_data = self.run_validation(self.initial_data)---》Serializer的run_validation---》两句重要的话:value = self.to_internal_value(data);value = self.validate(value)---》这两句话就是局部钩子和全局钩子-...
city_serializer = DrfCitySerializer(data=req.data) if city_serializer.is_valid(): # 插入数据 DrfCity.objects.create(**city_serializer.validated_data) # 把插入的数据返回给调用者 return Response(city_serializer .data) else: return Response(city_serializer.errors) 22.【drf-删除数据】 删除数据比较...
is_valid(): # 重写update方法才能存入 ser.save() return Response(ser.data) return Response({'code':101,'msg':'校验未通过','error':ser.errors}) 路由 代码语言:javascript 复制 path('books1/', views.BookView1.as_view()), path('books1/<int:pk>', views.BookDetailView1.as_view()), ...
Serializer(instance=bookobj,data=request.data)ifser.is_valid():ser.save()returnResponse({'code':100,'msg':'putok','data':request.data})returnResponse({'code':101,'msg':ser.errors})defdelete(self,request,pk):models.Book.objects.filter(pk=pk).delete()classPublishView(APIView):print('...
is_valid() 校验数据是否合法 save() 保存之前,必须先调用is_valid(),保存后返回一个Goods object对象 def post(self, request, *args, **kwargs): """提交数据""" verify_data = GoodsSerializer(data=request.data) 1. 2. 3. 上面这个过程,用户传过来的数据先清洗,校验数据合法性,再存入数据库的过程...
()`. ''This may be because you have a writable field on the ''serializer class that is not a valid argument to ''`%s.%s.create()`. You may need to make the field ''read-only, or override the %s.create() method to handle ''this correctly.\nOriginal exception was:\n %s'%(...
:param str type: parameter type; required if `in_` is not ``body``; must not be ``object``:param str format: value format, see OpenAPI spec :param list enum: restrict possible values :param str pattern: pattern if type is ``string``:param .Items items: only valid if `type` is ...
serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. ...
serializer.is_valid(raise_exception=True)exceptException as e:returnJsonResponse(serializer.errors)#校验成功之后的数据, 可以使用validated_data属性来获取#1. 如果在创建序列化器对象的时候, 只给data传参, 那么调用save()方法,#实际调用的就是序列化器对象的create()方法#serializer.save(user="孤鹰", age=...