mirror of
https://github.com/django/django.git
synced 2025-04-26 02:04:38 +00:00
Document db_default behavior in BooleanField
This commit is contained in:
parent
b6ad8b687a
commit
e4ab2cef99
@ -690,15 +690,38 @@ case it can't be included in a :class:`~django.forms.ModelForm`.
|
|||||||
``BooleanField``
|
``BooleanField``
|
||||||
----------------
|
----------------
|
||||||
|
|
||||||
.. class:: BooleanField(**options)
|
class BooleanField(**options)
|
||||||
|
|
||||||
A true/false field.
|
A true/false field.
|
||||||
|
|
||||||
The default form widget for this field is :class:`~django.forms.CheckboxInput`,
|
The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True.
|
||||||
or :class:`~django.forms.NullBooleanSelect` if :attr:`null=True <Field.null>`.
|
|
||||||
|
|
||||||
The default value of ``BooleanField`` is ``None`` when :attr:`Field.default`
|
The default value of BooleanField is None when Field.default isn’t defined.
|
||||||
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``
|
``CharField``
|
||||||
-------------
|
-------------
|
||||||
|
Loading…
x
Reference in New Issue
Block a user