- 1.自定义
class TitleValidator(object):
def __init__(self,start):
self.start = start
def __call__(self, value):
if not value.startswith(self.start):
message = '标题必须以 %s 为开头。' % self.start
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={'required':'组名不能为空'},validators=[TitleValidator('test'),])
class UserGroupView(APIView):
def post(self,request,*args,**kwargs):
ser = UserGroupSerializer(data=request.data)
if ser.is_valid():
print(ser.validated_data['title'])
return HttpResponse("提交成功")
else:
print(ser.errors) # {'title': [ErrorDetail(string='标题必须以 test 为开头。', code='invalid')]}
return HttpResponse(ser.errors)
- 2.基于ModelSerializer
class TitleValidator(object):
def __init__(self,start):
self.start = start
def __call__(self, value):
if not value.startswith(self.start):
message = '标题必须以 %s 为开头。' % self.start
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.ModelSerializer):
class Meta:
model = models.UserGroup
fields = '__all__'
depth = 1
extra_kwargs = {'title': {'validators': [TitleValidator('test'), ]}}
class UserGroupView(APIView):
def post(self,request,*args,**kwargs):
ser = UserGroupSerializer(data=request.data)
if ser.is_valid():
print(ser.validated_data['title'])
return HttpResponse("提交成功")
else:
print(ser.errors) # {'title': [ErrorDetail(string='标题必须以 test 为开头。', code='invalid')]}
return HttpResponse(ser.errors)
- 3.钩子函数
class UserGroupSerializer(serializers.Serializer):
title = serializers.CharField()
# 钩子函数,validate + “_” + 字段名称
def validate_title(self,value):
if not value.startswith("test"):
message = '标题必须以 test 为开头'
raise serializers.ValidationError(message)
class UserGroupView(APIView):
def post(self,request,*args,**kwargs):
ser = UserGroupSerializer(data=request.data)
if ser.is_valid():
print(ser.validated_data['title'])
return HttpResponse("提交成功")
else:
print(ser.errors) # {'title': [ErrorDetail(string='标题必须以 test 为开头。', code='invalid')]}
return HttpResponse(ser.errors)
标签:__,10,ser,title,self,rest,start,序列化,def
From: https://www.cnblogs.com/xwltest/p/18229748