diff options
author | Ian Foote <python@ian.feete.org> | 2020-11-22 22:27:57 +0000 |
---|---|---|
committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2023-05-12 19:11:40 +0200 |
commit | 7414704e88d73dafbcfbb85f9bc54cb6111439d3 (patch) | |
tree | f51136b16e457d7f46e01ff3cc06308faf0923db /docs/ref/models/fields.txt | |
parent | 599f3e2cda50ab084915ffd08edb5ad6cad61415 (diff) | |
download | django-7414704e88d73dafbcfbb85f9bc54cb6111439d3.tar.gz |
Fixed #470 -- Added support for database defaults on fields.
Special thanks to Hannes Ljungberg for finding multiple implementation
gaps.
Thanks also to Simon Charette, Adam Johnson, and Mariusz Felisiak for
reviews.
Diffstat (limited to 'docs/ref/models/fields.txt')
-rw-r--r-- | docs/ref/models/fields.txt | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 27b87c1f53..344cc45280 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -351,6 +351,38 @@ looking at your Django code. For example:: db_comment="Date and time when the article was published", ) +``db_default`` +-------------- + +.. versionadded:: 5.0 + +.. attribute:: Field.db_default + +The database-computed default value for this field. This can be a literal value +or a database function, such as :class:`~django.db.models.functions.Now`:: + + created = models.DateTimeField(db_default=Now()) + +More complex expressions can be used, as long as they are made from literals +and database functions:: + + month_due = models.DateField( + db_default=TruncMonth( + Now() + timedelta(days=90), + output_field=models.DateField(), + ) + ) + +Database defaults cannot reference other fields or models. For example, this is +invalid:: + + end = models.IntegerField(db_default=F("start") + 50) + +If both ``db_default`` and :attr:`Field.default` are set, ``default`` will take +precedence when creating instances in Python code. ``db_default`` will still be +set at the database level and will be used when inserting rows outside of the +ORM or when adding a new field in a migration. + ``db_index`` ------------ @@ -408,6 +440,9 @@ The default value is used when new model instances are created and a value isn't provided for the field. When the field is a primary key, the default is also used when the field is set to ``None``. +The default value can also be set at the database level with +:attr:`Field.db_default`. + ``editable`` ------------ |