-->

Why Model field validation happens before validate

2019-08-06 11:44发布

问题:

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)