DRF - 序列化之自定义校验规则
views.py:
# 自定义规则 class TestValidator(object): def __init__(self, base): self.base = base def __call__(self, value): # 规则明细 if not value.startswith(self.base): message = "内容必须以 %s 为开头" % self.base raise serializers.ValidationError(message) def set_context(self, serializer_field): """ This hook is called by the serializer instance, prior to the validation call being made. """ # 执行验证之前调用,serializer_fields 是当前字段对象 pass class UserGroupSerializer(serializers.Serializer): title = serializers.CharField( error_messages={"blank": "内容不能为空"}, validators=[TestValidator("AAAAA"),], # 设置规则 ) class UserGroupView(APIView): def post(self, request, *args, **kwargs): ser = UserGroupSerializer(data=request.data) if ser.is_valid(): # 如果 ser 有数据 print(ser.validated_data["title"]) else: print(ser.errors) # 如果没数据,则打印错误信息 return HttpResponse("ok")
提交不合规定的数据: