如何根据同一模型中其他字段的值设置django模型字段值

时间:2015-02-17 19:51:08

标签: python django

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

  1. 如果scamTrue,则whitelist的允许值为FalseNone
  2. 如果scamFalse,则whitelist的允许值为TrueNone
  3. 如果scamNone,则whitelist的允许值为TrueFalseNone
  4. 那么,如何确保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)
    

2 个答案:

答案 0 :(得分:1)

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

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.")

使用truth table更新您的问题,以便我们了解您的需求。

答案 1 :(得分:1)

您可以为以下代码创建属性 getter和setter,类似于以下代码:

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