Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
Juanjo Conti Avatar asked Nov 22 '09 15:11

Juanjo Conti


People also ask

How to define Boolean field in Django?

The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True. The default value of BooleanField is None when Field. default isn't defined. One can define the default value as true or false by setting the default attribute to true/false simultaneously.

How do I use the toggle switch in Django Boolean field?

If you want to change the boolean field value is_working on click, you need to use Jquery. I created an app named toggle , so you need to replace it with your app's name. when you click the Currently working here? check box, will instantly change the boolean field value "is_working".

What is NullBooleanField?

NullBooleanField in Django Forms is a select field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is NullBooleanSelect. It normalizes to: A Python True or False value.

What is a model Django?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .


2 Answers

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
like image 82
jathanism Avatar answered Nov 13 '22 15:11

jathanism


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
like image 38
SingleNegationElimination Avatar answered Nov 13 '22 14:11

SingleNegationElimination