在django中创建时检查模型的字段以填充在一起

mrfwxfqh  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(110)

我想以这种方式为我的模型创建条件(仅用于创建):字段A、B、C和D字段在一起(不为空),字段E、F、G和H字段在一起。因此,我们可以有

input=    (somthingA,somthingB,somthingC,somthingD,None,None,None,None)

input=   (None,None,None,None,somthingE,somthingF,somthingG,somthingH)

如果一个或多个文件为空,则返回错误:

input=(somthingA,None,somthingC,somthingD,None,None,None,None)

错误:条件1下B字段不能为空

qjp7pelc

qjp7pelc1#

您可以将此条件添加到模型clean()方法中

from django.core.exceptions import ValidationError
from django.db import models

class YourModel(models.Model):
    ...

    def clean(self):
        if not (self.A and self.B and self.C and self.D) and not (self.E and self.F and self.G and self.H):
            raise ValidationError("Fields A, B, C, D or fields E, F, G, H must be filled together.")
        if (self.A or self.B or self.C or self.D) and (self.E or self.F or self.G or self.H):
            raise ValidationError("Fields A, B, C, D cannot be filled together with fields E, F, G, H.")

相关问题