← Back to Django, page 3

django-0048 · Hard senior

What are GeneratedField and db_default in Django 5.0, and when would you use them instead of Python-side defaults or computed properties?

db_default sets a default value in the database schema, so rows inserted by any client (raw SQL, other services) get it, and it can be an expression such as Now(). GeneratedField defines a column computed by the database from other columns, either stored or virtual, so it is always consistent and can be indexed and filtered. Use them when the value must be correct no matter which code writes the row.

Full answer

Both arrived in Django 5.0 and move logic from Python into the database.

db_default

  • created = models.DateTimeField(db_default=Now()) adds DEFAULT CURRENT_TIMESTAMP to the column.
  • Compare with default=, which Django fills in Python before INSERT. Rows inserted by raw SQL, a data pipeline or another service do not get Python defaults.
  • On insert, backends that support RETURNING (PostgreSQL, SQLite 3.35+, MariaDB 10.5+) send the database-chosen value back, so the instance has it right away. On MySQL, call refresh_from_db() to read it.
  • If both default and db_default are set, Python's default is used for ORM inserts, while the database default covers other writers.

GeneratedField

python
total = models.GeneratedField(
    expression=F("theory") + F("practical"),
    output_field=models.IntegerField(),
    db_persist=True,
)
  • The database computes the value. db_persist=True stores it (PostgreSQL only supports stored generated columns); False makes a virtual column computed on read where supported (SQLite, MySQL, Oracle).
  • You cannot assign it; it is read-only.
  • It can be indexed and used in filter() and order_by() like any column, unlike a Python @property.
  • On insert, the value comes back through RETURNING where supported. After an update in Django 5.2 the instance keeps the old value (the snippet shows this), so call refresh_from_db(). Django 6.0 refreshes generated fields after save() on PostgreSQL, SQLite and Oracle.
  • The expression must be deterministic and use only columns of the same row.

When to choose a @property instead: values that depend on other tables, change with time ("days until fee due"), or are only displayed, never filtered.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import connection, models
from django.db.models import F, Value
from django.db.models.functions import Concat, Now


class ExamResult(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    theory = models.IntegerField()
    practical = models.IntegerField()
    status = models.CharField(max_length=10, db_default="pending")
    created = models.DateTimeField(db_default=Now())
    total = models.GeneratedField(expression=F("theory") + F("practical"),
                                  output_field=models.IntegerField(), db_persist=True)
    full_name = models.GeneratedField(expression=Concat("first_name", Value(" "), "last_name"),
                                      output_field=models.CharField(max_length=61), db_persist=False)

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(ExamResult)

r = ExamResult.objects.create(first_name="Nikhil", last_name="Das", theory=58, practical=27)
print(r.full_name, r.total, r.status, r.created is not None)

# A writer outside the ORM still gets the database default and the computed columns
with connection.cursor() as cur:
    cur.execute(f"INSERT INTO {ExamResult._meta.db_table} (first_name, last_name, theory, practical) "
                "VALUES ('Pooja', 'Rao', 70, 25)")
print(list(ExamResult.objects.filter(total__gte=90).values_list("full_name", "total", "status")))

r.theory = 65
r.save()
print("after update, before refresh:", r.total)   # Django 5.2 keeps the old value
r.refresh_from_db()
print("after update:", r.total)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Nikhil Das 85 pending True [('Pooja Rao', 95, 'pending')] after update, before refresh: 85 after update: 92

Key points

  • db_default is a database-level default, also applied to non-Django writers
  • Python default= only applies to ORM inserts
  • GeneratedField is computed by the database from same-row columns
  • Generated columns are read-only and can be indexed and filtered
  • PostgreSQL supports only stored generated columns

Common mistakes

  • Assuming Python default= protects rows inserted by raw SQL or other services
  • Trying to assign a value to a GeneratedField
  • Reading a generated value after an update in Django 5.2 without refresh_from_db()
  • Using db_persist=False on PostgreSQL, which only supports stored generated columns

Follow-ups

  • What is the difference between a GeneratedField and an annotation?
  • How would you add a db_default column to a large table safely?
  • Which expressions are not allowed in a generated column?

Tips

  • Explain the difference from Python defaults with an outside writer
  • Mention indexing and filtering as the edge over @property
  • Note the version: both are Django 5.0+