When to use NullBooleanField in Django
Django 2.1 introduced null=True
for BooleanField
. Using NullBooleanField
is now discouraged.
So use, x = BooleanField(null=True)
instead of x = NullBooleanField()
Here's a simple use case: If you only need to record the "Yes" or "No" status, use Boolean without null. But if you want to have 3 conditions say, "Yes", "No", and "Don't Know", use it with null=True
.
I think you should use NullBooleanField
only when you have three possible choices: Unknown, Yes (True) and No (False).
In your case you have only two possible values - Yes (user has drunk water) and No (user has NOT drunk water) so a BooleanField
would be better.
One more reason to use a BooleanField
in your case is because the default form widget for this field is a CheckboxInput
(docs), while the default form widget for a NullBooleanField
is a NullBooleanSelect
(docs). And since you use a checkbox, a BooleanField
would do the job better.
The question you need to answer to find out whether you should use the BooleanField
or the NullBooleanField
is actually concerning the possible states of the value of the field you want to represent in your model:
2 possible states:
- user has drunk water
- user has not drunk water
→ use BooleanField
3 possible states:
- user has drunk water
- user has not drunk water
- it is not known whether the user has or has not drunk water
→ use NullBooleanField
.
UPDATE:
NullBooleanField
is deprecated in version 3.1. Instead use BooleanField
with null=True
.