【问题标题】:Python - Django - Model BooleanField Dependent On Other BooleanField In Same ModelPython - Django - 模型 BooleanField 依赖于同一模型中的其他 BooleanField
【发布时间】:2017-02-12 17:59:50
【问题描述】:

我正在使用 Django 编写一个 Web 应用程序,并且想知道是否可以在模型中拥有一个 BooleanField,其值将基于同一模型中的其他 BooleanField。

基本上,我希望模型中的一个 BooleanField 只有在模型中的所有其他 BooleanField 都为 True 时才为 True。

例如,下面的模型:

class ModelEx(models.Model):
   booleanA = models.BooleanField(default=False)
   booleanB = models.BooleanField(default=False)
   booleanC = models.BooleanField(default=False)
   booleanD = models.BooleanField(default=False)

只有当 booleanB 和 booleanC 和 booleanD 为 True 时,我才希望 booleanA 为 True。

我还没有找到任何有关此的信息,所以如果有人知道是否有解决方案,那就太好了。

谢谢。

【问题讨论】:

    标签: python django boolean models


    【解决方案1】:

    您可以覆盖模型的保存方法。

    class ModelEx(models.Model):
       booleanA = models.BooleanField(default=False)
       booleanB = models.BooleanField(default=False)
       booleanC = models.BooleanField(default=False)
       booleanD = models.BooleanField(default=False)
    
       def save(self, *args, **kwargs):
           self.booleanA = self.booleanA and self.booleanB and self.booleanC
           return super(ModelEx, self).save(*args, **kwargs)
    

    【讨论】:

    • 不要在 save 中传递 kwargs,而是执行 def save(self, *args, **kwargs) 然后调用父母的 save super(ModelEx, self).save(*args, **kwargs)
    • 另外,True + True + True 是 3 而不是 True。如果例如booleanDFalse,那么 booleanA 将是 2。请改用 self.booleanB and self.booleanC and self.booleanD
    • 感谢如此敏锐的眼睛。
    • 感谢大家的cmets。 @Bipul 我会验证你的答案,因为它确实让我朝着正确的方向前进。 Evans Murithi 的评论确实是正确的,因此也感谢您给出了确切的答案。不过我还有一个问题。直接从 DB 界面修改数据时,将所有字段更改为 true 不会将字段 A 更改为 true(即使在视图函数触发更改时它可以正常工作)。你知道为什么吗?
    【解决方案2】:

    您可以覆盖模型的保存方法。会是这样的。

    def save(self, *args, **kwargs):
       self.booleanA = self.booleanB and self.booleanC and self.booleanD
       return super(ModelEx, self).save(*args, **kwargs)
    

    【讨论】:

    • 嗨,shivam,非常感谢您的回答。这是正确的,但已经提供了答案,所以我将第一个标记为正确的。
    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2013-03-31
    • 2021-06-07
    • 2010-11-30
    • 2015-08-11
    相关资源
    最近更新 更多