Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use NullBooleanField in Django

I have a button that, when clicked, should save in the database that the user has drunk water. I just wanted to check whether NullBooleanField would be the correct way to define this.

A broader question that if answered would be useful to the community is a list of optimal circumstances under which to use NullBooleanField. But I'm not asking that here. Just in case you wanted a better challenge.

Thank you in advance.

like image 643
thebot Avatar asked Mar 09 '18 16:03

thebot


2 Answers

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.

like image 197
bonidjukic Avatar answered Nov 08 '22 01:11

bonidjukic


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.

like image 10
Nitin Nain Avatar answered Nov 08 '22 01:11

Nitin Nain