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.
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.
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 ().
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.
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.
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,)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With