MySQL Django模型中的布尔字段?

5

是的,我确实阅读了链接中提供的 MySQL 用户信息。 - Juanjo Conti
4个回答

7
您可以为您的模型创建自己的方法来为您评估此内容:
class User(models.Model):
    active_status = models.BooleanField(default=1)

    def is_active(self):
        return bool(self.active_status)

那么,您对该字段执行的任何测试只需引用该方法即可:

>>> u.is_active()
True

You can even make this into a property:

class User(models.Model):
    active_status = models.BooleanField(default=1)

    @property    
    def is_active(self):
        return bool(self.active_status)

这样做的好处是,类的用户甚至不需要知道它是作为一个方法实现的:

>>> u.is_active
True

1

你是否预计这种情况会根据类型导致不同的行为?

>>> 1 == True
True
>>> 0 == False
True
>>> int(True)
1
>>> int(False)
0

1

这里是针对NullBooleanField进行调整的上述方法:

result = models.NullBooleanField()

def get_result(self):
    if self.result is None:
        return None
    return bool(self.result)

0
>>> u=User.objects.get(pk=1)
>>> u.is_active
1
>>> u.is_active==1
True
>>>

布尔列返回 1 或 0 的原因在你问题的链接中。

你的例子应该是:u.is_active == True。 - Juanjo Conti
是否可以将布尔字段隐式转换为True或False,而不是1或0? - Rama Vadakattu
Juanjo,我把它列为一个例子,说明如何实现True或False的结果。 Rama,我猜通过修改Django的模型代码应该是可能的,但是我不知道有这样的解决方案。 - fest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接