我想在BaseSerializer中使用自定义验证器。
第一次尝试:
定制验证器:
class UserIdExists:
def __init__(self):
self.MESSAGE_INCORRECT_USER = 'No user with this id.'
def __call__(self, user_id):
exists = User.objects.filter(id=user_id).exists()
if not exists:
message = self.MESSAGE_INCORRECT_USER
raise serializers.ValidationError(message, code='invalid')
和BaseSerializer:
class QuestionBaseSerializer(serializers.BaseSerializer):
def to_internal_value(self, data):
user_id = data.get('user_id')
user_validator = UserIdExists()
user_validator(user_id=user_id)
在验证错误的情况下,我收到一条消息:
'["No user with this id."]'
但我希望收到这样的信息:
'{"user_id": "No user with this id."}'
第二次尝试:自定义验证器:
class UserIdExists:
def __init__(self):
self.MESSAGE_INCORRECT_USER = 'No user with this id.'
def __call__(self, user_id, field=None):
exists = User.objects.filter(id=user_id).exists()
if not exists:
if field:
message = {field: self.MESSAGE_INCORRECT_USER}
raise serializers.ValidationError(message, code='invalid')
else:
if not field:
message = self.MESSAGE_INCORRECT_USER
raise serializers.ValidationError(message, code='invalid')
和BaseSerializer:
class QuestionBaseSerializer(serializers.BaseSerializer):
def to_internal_value(self, data):
user_id = data.get('user_id')
user_validator = UserIdExists()
user_validator(user_id=user_id, field='user_id')
我得到了预期的消息:
'{"user_id": "No user with this id."}'
我做的对吗?还能做得更正确吗?
与其使用to_internal_value
,不如使用专门为验证而设计的功能,这样更容易扩展/维护,因为您只需关注验证逻辑,而不是如何生成内部值。验证字段的约定是:
- 序列化器字段属性验证器(要为字段运行的验证器列表)
- 序列化方法validate_field_name()
- 序列化方法
validate()
这里为了简化解释,我们将验证只允许奇数user_id
。
class UserIdExists:
def __init__(self):
self.MESSAGE_INCORRECT_USER = 'No user with this id.'
def __call__(self, user_id):
if user_id % 2 == 0:
raise serializers.ValidationError("No user with this id.")
return user_id
class QuestionBaseSerializer(serializers.Serializer):
user_id = serializers.IntegerField(
validators=[UserIdExists()]
)
class MathQuestionSerializer(QuestionBaseSerializer):
description = serializers.CharField()
>>> from my_app.serializers import MathQuestionSerializer
>>>
>>> serializer = MathQuestionSerializer(data={'user_id': 2, 'description': "What is an imaginary number?"})
>>> serializer.is_valid(raise_exception=True)
Traceback (most recent call last):
raise ValidationError(self.errors)
rest_framework.exceptions.ValidationError: {'user_id': [ErrorDetail(string='No user with this id.', code='invalid')]}
>>>
>>> serializer = MathQuestionSerializer(data={'user_id': 3, 'description': "What is an imaginary number?"})
>>> serializer.is_valid(raise_exception=True)
True
正如您所看到的,从QuestionBaseSerializer
继承可以工作,因为它正确地自动验证了user_id
字段,确保它不是偶数。
您可以通过实现validate_field_name()
:
class QuestionBaseSerializer(serializers.Serializer):
user_id = serializers.IntegerField()
def validate_user_id(self, user_id: int) -> int:
validator = UserIdExists()
return validator(user_id)
class MathQuestionSerializer(QuestionBaseSerializer):
description = serializers.CharField()
def validate_user_id(self, user_id: int) -> int:
# Let's call the usual validation of even-odd numbers
user_id_validated = super().validate_user_id(user_id)
# Now, let's add additional validation of small numbers
if user_id_validated < 10:
raise serializers.ValidationError("No user with this id.")
return user_id_validated
>>> serializer = MathQuestionSerializer(data={'user_id': 2, 'description': "What is an imaginary number?"})
>>> serializer.is_valid(raise_exception=True)
Traceback (most recent call last):
raise ValidationError(self.errors)
rest_framework.exceptions.ValidationError: {'user_id': [ErrorDetail(string='No user with this id.', code='invalid')]}
>>>
>>> serializer = MathQuestionSerializer(data={'user_id': 3, 'description': "What is an imaginary number?"})
>>> serializer.is_valid(raise_exception=True)
Traceback (most recent call last):
raise ValidationError(self.errors)
rest_framework.exceptions.ValidationError: {'user_id': [ErrorDetail(string='No user with this id.', code='invalid')]}
>>>
>>> serializer = MathQuestionSerializer(data={'user_id': 14, 'description': "What is an imaginary number?"})
>>> serializer.is_valid(raise_exception=True)
Traceback (most recent call last):
raise ValidationError(self.errors)
rest_framework.exceptions.ValidationError: {'user_id': [ErrorDetail(string='No user with this id.', code='invalid')]}
>>>
>>> serializer = MathQuestionSerializer(data={'user_id': 15, 'description': "What is an imaginary number?"})
>>> serializer.is_valid(raise_exception=True)
True
正如您所看到的,验证正确地检查了它是奇数(基本验证)还是大于10(子类验证)。