简体   繁体   中英

Boolean fields in MySQL Django Models?

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

Here is the above method adapted for NullBooleanField :

result = models.NullBooleanField()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM