繁体   English   中英

如何基于同一模型中其他字段的值设置Django模型字段值

[英]How to set django model field value based-on value of other field in the same Model

我想分配一个NullBooleanField值以始终与同一模型中的其他字段值相反,除了None之外。 从下面的模型中,我想确定scam的值是否为Truewhitelist的值也不能为True 但是,如果scam为“ None ,则允许whitelist也设置为“ None 预期的标准是以下之一:

  1. 如果scamTrue ,则whitelist的允许值为FalseNone
  2. 如果scamFalse ,则whitelist的允许值为TrueNone
  3. 如果scamNone ,则whitelist的允许值为TrueFalseNone

因此,如何确保scam始终与whitelist相反?

这是我的课堂模型:

class ExtendHomepage(models.Model):
    "extending homepage model to add more field"
    homepage = models.OneToOneField(Homepage)

    # True if the website is a scam, False if not, None if not sure
    scam = models.NullBooleanField(blank=True, null=True)

    # True if the webpage is already inspected, False if not 
    inspected = models.BooleanField(default=False)

    # True if the website is already reported, False if not yet 
    reported =  models.NullBooleanField(blank=True, null=True)

    # True if the website response is 200, else it is False
    access =  models.BooleanField(default=True)

    # True if the web should be whitelist, False if should not, None pending
    whitelist =  models.NullBooleanField(blank=True, null=True)

为此,您可以使属性获取器和设置器类似以下代码:

class ExtendHomepage(models.Model):
    "extending homepage model to add more field"
    homepage = models.OneToOneField(Homepage)

    # True if the website is a scam, False if not, None if not sure
    scam = models.NullBooleanField(blank=True, null=True)

    # True if the webpage is already inspected, False if not 
    inspected = models.BooleanField(default=False)

    # True if the website is already reported, False if not yet 
    reported =  models.NullBooleanField(blank=True, null=True)

    # True if the website response is 200, else it is False
    access =  models.BooleanField(default=True)

    # True if the web should be whitelist, False if should not, None pending

    __whitelist = models.NullBooleanField(blank=True, null=True)

    @property
    def whitelist(self):
        if self.scam is not None and self.scam == self.__whitelist:
            # this if block is not necessary but for 
            # check if content changed directly in database manager
            # then assign None value to this attribute
            self.__whitelist = None
        return self.__whitelist

    @whitelist.setter
    def whitelist(self, value):
        self.__whitelist = value
        if self.scam is not None and self.scam == self.__whitelist:
            self.__whitelist = None

我不确定我是否了解您的标准,但是您可以使用验证:

def clean(self):
    if self.scam and self.whitelist:
        raise ValidationError("Can't set whitelist and scam simultaneously.")
    if self.scam is False and self.whitelist is False:
        raise ValidationError("Negate either whitelist or scam or none.")

使用真值表更新您的问题,以便我们了解您的需求。

暂无
暂无

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

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