4

I have a BooleanField on Question model:

class Question(models.model):
    is_deleted = BooleanField()

Why does it accept non-boolean type python object?

>>>que_obj = Question.objects.create()
>>>que_obj.is_deleted='yes'
>>>que_obj.save()
>>>que_obj.is_deleted
>>>'yes'
ramganesh
  • 741
  • 1
  • 8
  • 33

2 Answers2

2

A model instance is just a python object. You can set any attribute to any value.

When you save the instance, all data is converted to the appropriate data types to Django's best ability. For a BooleanField this means that any truthy value (bool(value) is True) is saved as True and any falsy value (bool(value) is False) is saved as False.

When you save a model, the current values of the field is read, converted to an appropriate data type, and saved to the database. The original value of the field is not altered. When you reload the model from the database, the field will have the actual value saved in the database: True.

knbk
  • 52,111
  • 9
  • 124
  • 122
  • yes. Converted to bool type. so you say its possible to set any attribute to any value?? – ramganesh Sep 03 '15 at 07:28
  • 1
    On a python level - yes. When you save the object, and the value is converted to a database value, you might run into an error for some field types. For example, Django can't convert `'yes'` to a valid datetime object for a `DateTimeField`. A `BooleanField` doesn't have that problem (`bool(value)` works on any python value), so you won't get any errors there. – knbk Sep 03 '15 at 09:30
  • clear now :) great answer. Django have method for converting value to right type. – ramganesh Sep 03 '15 at 10:35
0

peter is right- your line:

que_obj.is_deleted='yes'

will override the boolean value to now contain the string 'yes'. You can check the boolean value with the bool() function like below:

que_obj.is_deleted=bool('yes')

Here's the docs entry for bool()

Community
  • 1
  • 1
GHandel
  • 172
  • 2
  • 3
  • 13