简体   繁体   English

向Django模型添加验证

[英]Add validations to Django model

I am using django rest framework for an app. 我正在为应用程序使用django rest框架。 Below is the Feature model : 以下是功能模型

class Feature(models.Model):
    image_component = models.ForeignKey('Image_Component',on_delete=models.CASCADE,)
    feature_type = models.CharField(max_length = 20 )
    feature_value = models.CharField(max_length = 30)


    def save(self , *args , **kwargs):
        if not self.feature_type in ['size','quality','format']:
            raise Exception("Incorrect")
        else:
            super(Feature, self).save(*args , **kwargs)

    def validate(self , data):
        if data['feature_type'] == 'size':
            print self.feature_value.is_alnum()
            if not data['feature_value'].is_alnum():
                raise serializers.ValidationError('Incorrect value')
        return data

The serializer class for feature model is : 特征模型的序列化器类是:

class FeatureSerializer(serializers.ModelSerializer):
    class Meta:
        model = Feature
        field = ('id','feature_value')

Below is the corresponding view : 下面是对应的视图:

class Feature(generics.ListCreateAPIView):
    queryset = Feature.objects.all()
    serializer_class = FeatureSerializer

I want to validate the model such that if any user is inputing the value for feature_value as size then he/she can input it only in the form of "200x200"(if not this then alphanumeric). 我想验证模型,以便如果有任何用户正在输入feature_value的值作为大小,则他/她只能以“ 200x200”的形式输入(如果不是,则输入字母数字)。 I tried to do this in the validate function in Feature model but its not working.Can someone tell me how to rectify this error. 我尝试在功能模型的验证功能中执行此操作,但此功能无法正常工作。有人可以告诉我如何纠正此错误。

Also the print statement in the validate method doesn't print anything which means the validate method is not at all called as said in the doc. 而且validate方法中的print语句不会打印任何内容,这意味着完全没有按照文档中的说明调用validate方法。

Code not tested. 代码未经测试。 Using argument validators in CharField method 在CharField方法中使用参数验证器

def validate_feature_type(self , data):
        if data['feature_type'] == 'size':
            print self.feature_value.is_alnum()
            if not data['feature_value'].is_alnum():
                raise serializers.ValidationError('Incorrect value')

class Feature(models.Model):
    image_component = models.ForeignKey('Image_Component', on_delete=models.CASCADE,)
    feature_type = models.CharField(max_length = 2, validators=[validate_feature_type] )
    feature_value = models.CharField(max_length = 30)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM