Validator 在 Django Rest Framework 中不起作用,为什么?
Validator does not work in Django Rest Framework, why?
Django Rest Framework 文档指出 here:
Validators
Individual fields on a serializer can include validators, by declaring
them on the field instance, for example:
但是当我尝试这样做时:
class DetailSerializer(serializers.ModelSerializer):
name = serializers.Field(validators=[character_validator])
class Meta:
model = User
fields = ("id", "name")
我收到以下错误:
name = serializers.Field(validators=[character_validator])
TypeError: __init__() got an unexpected keyword argument 'validators'
如果您查看字段 Class,您会发现它不需要 'validators',但 CharField
、IntegerField
等需要。
尝试:
serializers.CharField(validators=[character_validator])
Django Rest Framework 文档指出 here:
Validators
Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
但是当我尝试这样做时:
class DetailSerializer(serializers.ModelSerializer):
name = serializers.Field(validators=[character_validator])
class Meta:
model = User
fields = ("id", "name")
我收到以下错误:
name = serializers.Field(validators=[character_validator])
TypeError: __init__() got an unexpected keyword argument 'validators'
如果您查看字段 Class,您会发现它不需要 'validators',但 CharField
、IntegerField
等需要。
尝试:
serializers.CharField(validators=[character_validator])