# 入口是 ser.is_valid(),是BaseSerializer的方法
# 最核心的代码
self._validated_data = self.run_validation(self.initial_data) # 切记不要按住ctrl点

# run_validation 调用的是Serializer类的方法
def run_validation(self, data=empty):
  value = self.to_internal_value(data) # 局部钩子的代码
  try:
    self.run_validators(value)
    value = self.validate(value) # 全局钩子的执行
    assert value is not None, '.validate() should return the validated data'
  except (ValidationError, DjangoValidationError) as exc:
    raise ValidationError(detail=as_serializer_error(exc))
    return value



# 局部钩子核心代码
for field in fields:
validate_method = getattr(self, 'validate_' + field.field_name, None) #反射字段的局部钩子方法
try:
if validate_method is not None:
validated_value = validate_method(validated_value) #执行局部钩子方法
except ValidationError as exc:
errors[field.field_name] = exc.detail
except DjangoValidationError as exc:
errors[field.field_name] = get_error_detail(exc)

posted on 2021-07-13 14:59  孟玉  阅读(307)  评论(0编辑  收藏  举报