MySQL Django 模型中的布尔字段?

5 投票
4 回答
16807 浏览
提问于 2025-04-15 16:15

在Django中,MySQL里的布尔字段其实是用一个叫TINYINT的小整数来存储的。当我从数据库里取出这个值时,我得到的是0或者1。难道我不应该得到False或者True吗?有没有办法让它变成这样呢?

4 个回答

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

你可以为你的模型创建一个自己的方法,这样就可以自动帮你评估这个内容:

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

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

然后你在测试这个字段时,只需要引用这个方法就可以了:

>>> u.is_active()
True

你甚至可以把它变成一个属性:

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

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

这样使用这个类的用户就不需要知道它是作为一个方法来实现的:

>>> u.is_active
True

撰写回答