1,在字段上定制字段信息的判断
class CreateManagerSerializers(serializers.ModelSerializer): username = serializers.CharField(validators=[UniqueValidator( queryset=models.Manager.objects.all(), message=‘名称重复‘ )]) password = serializers.CharField(write_only=True)
==>在传入库里面已经有的名字时,显示错误信息
{
"username": [
"名称重复"
]
}
2,在Meta中定制错误信息,效果和字段上定制一样
class Meta:
model = models.Manager
fields = [‘username‘, ‘password‘, ‘email‘, ‘mobile_number‘, ‘role_num‘, ‘channel‘]
extra_kwargs = {
‘username‘:{‘validators‘:[UniqueValidator(
queryset=models.Manager.objects.all(),
message=‘名称重复‘)]},
‘email‘: {‘validators‘: [UniqueValidator(
queryset=models.Manager.objects.all(),
message=‘email重复‘)]},
}
==>错误信息和上面一样
{
"username": [
"名称重复"
],
"email": [
"email重复"
]
}
3,利用valition_字段 raise报错信息
class CreateManagerSerializers(serializers.ModelSerializer): username = serializers.CharField() password = serializers.CharField(write_only=True) def validate_username(self,value): from rest_framework.exceptions import ValidationError flag=models.Manager.objects.filter(username=value).exists() if flag: raise ValidationError(‘用户名称重复‘) return value
==>报错信息
{
"username": [
"用户名称重复"
],
"email": [
"email重复"
]
}
django serializer 定制error_message
原文:https://www.cnblogs.com/52forjie/p/10432538.html