首页 > 解决方案 > 创建完美 django 自定义验证的问题

问题描述

我的会计应用程序有这个模型:

class Simpleunits(models.Model):
    User       = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    symbol     = models.CharField(max_length=32)
    formal     = models.CharField(max_length=32)

class Compoundunits(models.Model):
    User       = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    firstunit  = models.ForeignKey(Simpleunits,on_delete=models.CASCADE)
    conversion = models.DecimalField(max_digits=19,decimal_places=2)
    secondunit = models.ForeignKey(Simpleunits,on_delete=models.CASCADE)

class Stockdata(models.Model):
    User        = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    stock_name  = models.CharField(max_length=32)
    unitsimple  = models.ForeignKey(Simpleunits,on_delete=models.CASCADE,null=True,blank=True)
    unitcomplex = models.ForeignKey(Compoundunits,on_delete=models.CASCADE,null=True,blank=True)

我想在模型类 Stockdata 下创建一个自定义验证方法,如果用户同时提到 unitsimple 和 unitcomplex,那么他们将收到“只应给出一个单位”的验证错误,反之亦然......

我的意思是说,如果用户同时提及两个单元,则只能提及一个单元,无论是 unitsimple 还是 unitcomplex,那么他们将收到验证错误...

有谁知道我应该在 def clean(self) 函数下做什么来完成这个..???

先感谢您...

标签: djangodjango-modelsdjango-validation

解决方案


为 Stockdata 的创建视图创建一个模型表单,如您所说,添加一个自定义 clean() 方法,如下所示。

class CreateStockData(forms.ModelForm):
   class Meta:
       model = Stockdata        
       fields= [....]
   ....
   def clean(self):
       cleaned_data = super(CreateStockData, self).clean()
       unitsimple = cleaned_data.get('unitsimple')
       unitcomplex = cleaned_data.get('unitcomplex')
       if unitsimple != None and unitcomplex != None:
           raise forms.ValidationError({'unitcomplex':["You are not supposed to select both values!"]})

编辑

鉴于您的评论,让我以另一种方式发布。

class Stockdata(models.Model):
    ....
    def clean(self):
        if self.unitsimple is not None and if self.unitcomplex is not None:
            raise ValidationError(
                {'unitcomplex':["You are not supposed to select both values!"]})
    def save(self, *args, **kwargs):
        self.full_clean()
        super().save(*args, **kwargs)

请参阅验证对象


推荐阅读