From e4ab2cef99783afdba5b2d59b299b89fd51aa14c Mon Sep 17 00:00:00 2001 From: jcagado Date: Tue, 6 Aug 2024 20:02:43 -0700 Subject: [PATCH] Document db_default behavior in BooleanField --- docs/ref/models/fields.txt | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index e8b1cf8cba..992103b984 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -690,15 +690,38 @@ case it can't be included in a :class:`~django.forms.ModelForm`. ``BooleanField`` ---------------- -.. class:: BooleanField(**options) - +class BooleanField(**options) A true/false field. -The default form widget for this field is :class:`~django.forms.CheckboxInput`, -or :class:`~django.forms.NullBooleanSelect` if :attr:`null=True `. +The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True. -The default value of ``BooleanField`` is ``None`` when :attr:`Field.default` -isn't defined. +The default value of BooleanField is None when Field.default isn’t defined. + +.. note:: + + When using the `db_default` attribute, the field value will be an instance of `DatabaseDefault` before the instance is saved to the database. This means that a `bool()` evaluation of the field will not reflect the specified `db_default` value until the instance is saved. + + For example: + + .. code-block:: python + + from django.db import models + + class MyModel(models.Model): + my_field = models.BooleanField(db_default=False) + + my_obj = MyModel() + print(bool(my_obj.my_field)) # True, which is unexpected. + + my_obj.save() + print(bool(my_obj.my_field)) # False, as expected. + + To ensure the field value reflects the desired default before saving, also set the `default` attribute: + + .. code-block:: python + + class MyModel(models.Model): + my_field = models.BooleanField(default=False, db_default=False) ``CharField`` -------------