Why Model field validation happens before validate or validate_<field> is called?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 06:23:51

问题


I just started learning Django Rest Framework and I can't understand why DRF runs Model field validation before Own Validation I have a model which has a URLField and basically all I want to add http:// or https:// before it validates, so wrote custom validation method

class ShortenerSerializer(serializers.ModelSerializer):
    class Meta:
        extra_kwargs = {
            'count': {'read_only':True}
        }
        fields = ('id', 'url', 'short_url', 'count', 'created_at')
        model = Shortener

    def validate_url(self, url):
        if not 'http://' in url and not 'https://' in url:
            url = 'http://' + url
        url_validate = URLValidator()
        try:
            url_validate(url)
        except:
            raise serializers.ValidationError("Please Enter a Valid URL")
        return url

I even overide the validate method but again it is called after model field validation as it raises Exception. I guess i need to overide some method but no idea which one to override.


回答1:


You can override the is_valid method to avoid this behaviour

class ShortenerSerializer(serializers.ModelSerializer):
    def is_valid(self, *args, **kwargs):
        if self.initial_data.get('url'):
            # update self.initial_data with appended url

        return super(ShortenerSerializer, self).is_valid(*args, **kwargs)


来源:https://stackoverflow.com/questions/46909605/why-model-field-validation-happens-before-validate-or-validate-field-is-called

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