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

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

问题描述

目前的Django, MySQL中的布尔字段存储为TINYINT 。当我找回它,我得到0或1。我不应该得到虚实?有没有办法实现这种行为?

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?

推荐答案

您可以创建自己的方法,模型计算结果为你好:

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

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

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