Django / DRF - How can I view a list of all validators for a model / model serializer field?

百般思念 提交于 2019-12-13 18:35:04

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32928893/django-drf-how-can-i-view-a-list-of-all-validators-for-a-model-model-seria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!