MySQL Django模型中的布尔字段? [英] Boolean fields in MySQL Django Models?

查看:152
本文介绍了MySQL Django模型中的布尔字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您可以为您的模型创建自己的方法,为您评估: / p>

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

您甚至可以将其设为属性: p>

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

这篇关于MySQL Django模型中的布尔字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆