1.在create()中抛出错误
class YourSerializer(serializers.Serializer): def create(self, validated_data): # 进行数据验证是否满足条件 #得到数据过程以省略 condition = False if not condition: # 抛出ValidationError异常,并传递错误信息 raise ValidationError("错误信息") else: 正常逻辑
2.在valudate钩子中校验数据抛出错误
class YourSerializer(ModelSerializer): class Meta: model = Aaa exclude = ('is_delete', 'create_time',"modified_time" ) def validate(self, attrs): a = attrs.get('a') if len(a) < 10: raise ValidationError({'a': '该字段长度不能小于10'}) return attrs
2. 在视图中捕捉
from rest_framework.views import APIView from rest_framework.response import Response class YourView(APIView): def post(self, request): serializer = YourSerializer(data=request.data) try: if serializer.is_valid(): serializer.save() return Response(serializer.data) else: # 如果序列化器验证失败,获取错误信息 errors = serializer.errors return Response(errors, status=status.HTTP_400_BAD_REQUEST) except ValidationError as e: # 如果在序列化器的create方法中抛出了ValidationError异常,在这里捕获错误信息并返回给前端 errors = str(e.args[0]) # 获取错误信息 return Response(errors, status=status.HTTP_400_BAD_REQUEST)
标签:errors,ValidationError,抛出,错误信息,视图,django,序列化,serializer From: https://www.cnblogs.com/ltyc/p/17503099.html