我希望分配一个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 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)发布于 2015-02-17 20:03:08
我不确定我是否理解您的标准,但您可以使用验证:
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.")用真值表更新你的问题,这样我们就能理解你想要什么。
发布于 2015-02-17 20:15:04
为此,您可以制作一个属性、、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 = Nonehttps://stackoverflow.com/questions/28569940
复制相似问题