我正在为应用程序使用django rest框架。以下是功能模型:
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
要素模型的序列化程序类是:
class FeatureSerializer(serializers.ModelSerializer):
class Meta:
model = Feature
field = ('id','feature_value')
以下是相应的观点:
class Feature(generics.ListCreateAPIView):
queryset = Feature.objects.all()
serializer_class = FeatureSerializer
我想验证模型,以便任何用户输入 feature_value 的值为 size ,然后他/她只能以“200x200”的形式输入“(如果不是这个,那么字母数字)。我试图在功能模型的验证功能中执行此操作,但它无法正常工作。有人告诉我如何纠正此错误。
同样,validate方法中的print语句不会打印任何内容,这意味着完全没有调用validate方法,如文档中所述。
答案 0 :(得分:0)
代码未经测试。在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)