创建完美的 Django 自定义验证的问题

Problem in creating the perfect django custom validation

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

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)

我想在模型 class Stockdata 下创建一个自定义验证方法,如果用户同时提到 unitsimple 和 unitcomplex 那么他们将得到一个验证错误 "Only one unit should be given",反之亦然...

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

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

提前谢谢你...

为 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!"]})

编辑

鉴于您的评论,让我post换个方式。

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)

Validating objects