python MySQL Django 模型中的布尔字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1778948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:02:03  来源:igfitidea点击:

Boolean fields in MySQL Django Models?

pythonmysqldjangoboolean

提问by Juanjo Conti

At Django, a boolean field in MySQL is stored as a TINYINT. When I retrieve it, I get 0 or 1. Shouldn't I get False or True? Is there a way to achieve this behaviour?

在 Django,MySQL 中的布尔字段存储为 TINYINT。当我检索它时,我得到 0 或 1。我不应该得到 False 或 True 吗?有没有办法实现这种行为?

回答by jathanism

You could create your own method for your model that evaluates this for you:

您可以为您的模型创建自己的方法来为您评估:

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

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

Then any tests you perform against this field could just reference the method instead:

然后,您对该字段执行的任何测试都可以只引用该方法:

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

so that users of the class don't even have to know that it's implemented as a method:

这样类的用户甚至不必知道它是作为方法实现的:

>>> u.is_active
True

回答by asmoore82

Here is the above method adapted for NullBooleanField:

这是上述方法适用于NullBooleanField

result = models.NullBooleanField()

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

回答by SingleNegationElimination

Is there a situation you anticipate that this will cause different behaviour just based on the types?

您是否预计会出现仅基于类型而导致不同行为的情况?

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

回答by fest

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

The reasons why boolean columns return 1 or 0 are on the link in your question.

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