GeneratedField Deep Dive
Django 5.0 introduces GeneratedField, a field whose value is computed by the database. The field can be stored (persisted on disk) or virtual (computed on the fly). This replaces manual annotations or triggers.
Example
python
from django.db import models
from django.db.models import F, Value
from django.db.models.functions import Lower, Concat
class Product(models.Model):
name = models.CharField(max_length=200)
price_ht = models.DecimalField(max_digits=10, decimal_places=2)
tax_rate = models.DecimalField(max_digits=4, decimal_places=2)
# DB-computed field (stored)
price_ttc = models.GeneratedField(
expression=F('price_ht') * (1 + F('tax_rate')),
output_field=models.DecimalField(max_digits=10, decimal_places=2),
db_persist=True,
)
# Auto-generated slug (virtual)
name_lower = models.GeneratedField(
expression=Lower('name'),
output_field=models.CharField(max_length=200),
db_persist=False,
)
