Introduced in Django 5, this feature allows you to
use underlaying database functions to generate default values.
Using Database-Generated Default Values in Django
from django.db import models
from django.db.models.functions import Now
class Post(models.Model):
# ...
publish = models.DateTimeField(db_default=Now())
To set database-generated default values for a model field, Django provides the db_default
attribute instead of the regular default
attribute. The db_default
allows you to use database functions to generate the default value, rather than relying on Python code.
For example, you can use the Now
database function to automatically set a field's value to the current date and time. This serves a similar purpose to default=timezone.now
, but instead of relying on Python-generated datetimes, it uses the NOW()
function provided by the database itself to generate the initial value.
For more information on using the db_default
attribute, you can refer to the https://docs.djangoproject.com/en/5.0/ref/models/fi elds/#django.db.models.Field.db_default. Additionally, you can find a list of all available database functions in the https://docs.djangoproject.com/en/5.0/ref/models/da tabase-functions/.