Django / DRF - 如何查看模型/模型序列化程序字段的所有验证器的列表? [英] Django / DRF - How can I view a list of all validators for a model / model serializer field?

查看:1711
本文介绍了Django / DRF - 如何查看模型/模型序列化程序字段的所有验证器的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的UserExtendedSerializer:

  class UserExtendedSerializer(serializers.ModelSerializer):

def __init__ (self,* args,** kwargs):
super(UserExtendedSerializer,self).__ init __(* args,** kwargs)#在self.fields中调用super()
for field:#iterate通过序列化器字段
self.fields [field] .error_messages ['required'] ='输入有效的%s'%字段#设置自定义错误消息
self.fields [field] .error_messages ['invalid'] ='选择有效的%s'%字段#设置自定义错误消息
class Meta:
model = UserExtended
fields =('country',)

这是UserExtended模型:

  class UserExtended(models.Model):
user = models.OneToOneField(User)
country = models.ForeignKey(Country)

现在,当我尝试创建au在没有输入有效国家的情况下,Django给前端提供了一个错误,说不正确的类型。预期的pk值,接收到的列表,这个错误消息来自哪里?因为在我的init函数中,我覆盖了无效错误消息来说选择有效的国家,但这不是我收到的消息。 / p>

此外,我打开了shell,并执行

  repr(UserExtendedSerializer ())

,输出为:

  UserExtendedSerializer():\\\
country = PrimaryKeyRelatedField(queryset.Country.objects.all())

所以这里也没有列出Django验证器,我如何查看特定模型/模型序列化程序字段的所有验证器?

解决方案

获取特定序列化程序字段的验证器



要获取特定序列化程序字段的验证器,你可以这样做:

  my_field_validators = UserExtendedSerializer()。fields ['my_field']。validators 

获取所有序列化程序字段的验证器:



获取字典中所有序列化程序字段的验证器,我们可以使用字典理解。

  {x:y.validators for x ,y in UserExtendedSerializer()。fields.items()} 

获取序列化程序级验证器:



要获得在序列化程序级别定义的验证器,即序列化程序的 Meta 类中你可以这样做:

  UserExtendedSerializer()。validators 

但这不是错误来自哪里。



没有一个验证器是生成此错误消息。由于将无效数据传递到国家/地区字段的 UserExtendedSerializer 而发生错误。



DRF源代码 PrimaryKeyRelatedField

  class PrimaryKeyRelatedField(RelatedField):
default_error_messages = {
'required':_('这个字段是必需的)',
'does_not_exist':_(Invalid pk'{pk_value}' - 对象不存在),
'incorrect_type':_('不正确的类型,预期的pk值,收到{data_type}'),#错误消息
}

def to_internal_value(self,data):
try:
return self.get_queryset()。get(pk = data)
除了ObjectDoesNotExist:
self .fail('do_not_exist',pk_value = data)
except(TypeError,ValueError):#这里正在生成错误消息
self.fail('incorrect_type',data_type = type ).__ name__)

所以这个错误信息来自默认的 incorrect_type 错误消息。如果需要,可以使用此键更改错误消息。


This is my UserExtendedSerializer:

class UserExtendedSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
            super(UserExtendedSerializer, self).__init__(*args, **kwargs) # call the super() 
            for field in self.fields: # iterate over the serializer fields
                self.fields[field].error_messages['required'] = 'Enter a valid %s.'%field # set the custom error message
                self.fields[field].error_messages['invalid'] = 'Select a valid %s.'%field # set the custom error message
    class Meta:
        model = UserExtended
        fields = ('country',)

and this is the UserExtended model:

class UserExtended(models.Model):
    user = models.OneToOneField(User)
    country = models.ForeignKey(Country)

Now, when I try to create a user without entering a valid country, Django gives an error to the front end saying "Incorrect type. Expected pk value, received list". Where is this error message coming from? Because in my init function, I overrode the "invalid" error message to say "Select a valid country.", but that is not the message I receive.

Also, I opened up the shell and did

repr(UserExtendedSerializer())

and the output was:

UserExtendedSerializer():\n country = PrimaryKeyRelatedField(queryset.Country.objects.all())

So no Django validators were listed here either. How do I view all the validators for a specific model / model serializer field?

解决方案

Getting Validators for a particular serializer field:

To get the validators for a particular serializer field, you can do:

my_field_validators = UserExtendedSerializer().fields['my_field'].validators

Getting Validators for all the serializer fields:

To get the validators for all the serializer fields in a dictionary, we can use dictionary comprehension.

{x:y.validators for x,y in UserExtendedSerializer().fields.items()}

Getting serializer-level validators:

To get the validators defined at the serializer level i.e. in the Meta class of the serializer, you can do:

UserExtendedSerializer().validators

But this is not where the error comes from.

None of the validators are generating this error message. The error is occurring because of passing invalid data to UserExtendedSerializer for the country field.

DRF source code for PrimaryKeyRelatedField

class PrimaryKeyRelatedField(RelatedField):
    default_error_messages = {
        'required': _('This field is required.'),
        'does_not_exist': _("Invalid pk '{pk_value}' - object does not exist."),
        'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'), # error message
    }    

    def to_internal_value(self, data):
        try:
            return self.get_queryset().get(pk=data)
        except ObjectDoesNotExist:
            self.fail('does_not_exist', pk_value=data)
        except (TypeError, ValueError): # here error message is being generated
            self.fail('incorrect_type', data_type=type(data).__name__)

So this error message is coming from the default incorrect_type error message. You can use this key to change the error message if you want.

这篇关于Django / DRF - 如何查看模型/模型序列化程序字段的所有验证器的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆