我想分配一个 NullBooleanField 值以始终反对同一模型中的其他字段值,None 除外。从下面的模型中,我想确定 scam 的值是否为 True,whitelist 的值不能也为 True 。但是如果scam是None,whitelist允许也设置为None。预期条件是以下之一:
- 如果
scam为True,则whitelist的允许值为False或None - 如果
scam为False,则whitelist的允许值为True或None - 如果
scam为None,whitelist的允许值为True或False或None
那么,如何确保scam永远是whitelist的对立面呢?
这是我的类(class)模型:
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)
请您参考如下方法:
您可以为这种必要性制作一个属性 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
