为什么在验证或validate_< field>之前先进行模型字段验证叫做? [英] Why Model field validation happens before validate or validate_<field> is called?
问题描述
我刚刚开始学习Django Rest Framework,我不理解为什么DRF在自己进行验证之前先运行模型字段验证,所以我有一个带有URLField的模型,基本上我想添加http://或https://验证之前,因此编写了自定义验证方法
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
我什至覆盖了 validate 方法,但是在模型字段验证之后再次调用它,因为它引发了Exception.我想我需要重写某些方法,但不知道要重写哪个方法.
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.
推荐答案
您可以覆盖is_valid方法来避免这种行为
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)
这篇关于为什么在验证或validate_< field>之前先进行模型字段验证叫做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!