Django: Why does NullBooleanField accept non-boolean responses?

Say I have a NullBooleanField in a Zoo model:

class Zoo(models.model):
    lion = NullBooleanField()

Why does this allow me to save a non-Boolean field that is true by default, and not an error? For instance:

my_zoo = Zoo.objects.create()
my_zoo.lion = "Simba"
my_zoo.save() # Surprisingly, no error here.
>>>my_zoo.lion # True
+4
source share
1 answer

Because it NullBooleanFieldis simply trying to convert a Python object, in this case either None, Trueor False.

Thus, the casting boolwill work, will work in this field, because this is what it does in the background.


Edit:

. , , True, False, None, 't', 'f', 'True', 'False', 'None', '0' '1' ( 0 1!). Django 1.5. Django ?


2:

, Django 1.7, .

>>> zoo = Zoo.objects.create()
>>> zoo.lion = 'Simba'
>>> zoo.save()
>>> zoo.lion
'Simba'
>>> type(zoo.lion)
<type 'str'>

, . :

>>> zoo.walrus = 'Simba'
>>> zoo.walrus
'Simba'

, , :

>>> zoo = Zoo.objects.get(pk=1)
>>> zoo.lion
True
>>> type(zoo.lion)
<type 'bool'>

, . , to_python .

+5
source

All Articles