Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store null as default value againt Null boolean field

How to use NullBooleanField in Django models with SQLlite3, I want to store null as default value for the nullBoolean field, how do I do that?

I have migrated db from BooleanField to NullBooleanField, but it is still storing False as the default value.

Usage in the code is as:

LOCATOR_YES_NO_CHOICES = ((None,''), (True,'Yes'), (False, 'No'))
employed = models.NullBooleanField(choices=LOCATOR_YES_NO_CHOICES,
                                max_length=3,
                                blank=True, null=True, default="",)

Any example would be of great help.

like image 818
user3269734 Avatar asked Feb 06 '14 07:02

user3269734


People also ask

Is it possible to store null values in a Boolean?

Such as (true, false, unknown). Even if this is the case, if you are into ultra-normalization you will not allow any null values at all. Instead you'll store a true boolean in another table with a 1 to 1 relation.

When to use object to represent a nullable boolean?

to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context. each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like MessageFormat.format ().

What is the default value of nullbooleanfield in Django?

Note that for NullBooleanField, the default is blank=True, null=True, so you don't need to specify that. docs.djangoproject.com/en/2.0/_modules/django/db/models/fields/… Note that NullBooleanFIeld was deprecated in Django 3.1. It is recommended to use BooleanField (null=True). Agree that using BooleanField is the better move.

Is there anything wrong with just storing false as null?

ActiveOldestVotes 55 Is there anything inherently wrong with just storing false as null? Yes. If so can you please explain what the down side should be? NULL is not the same as False.


2 Answers

An empty string "" is not None

>>> "" is None
False

If you want the default to be None then write:

employed = models.NullBooleanField(choices=LOCATOR_YES_NO_CHOICES,
                                max_length=3,
                                blank=True, null=True, default=None,)
like image 158
oz123 Avatar answered Nov 03 '22 01:11

oz123


Note that NullBooleanFIeld was deprecated in Django 3.1. It is recommended to use BooleanField(null=True).

In this case;

employed = Models.BooleanField(null=True, default=None)
like image 40
Denis Kipkoech Biwott Avatar answered Nov 02 '22 23:11

Denis Kipkoech Biwott