I'm excited for the newly introduced Django db generated model fields (in Django 5.0) as it opens multiple new options. but I just bumped into a strange behavior.
consider this model
VAT.= 1.17
class Cost(models.Model):
price = DecimalField() # cut the definition for brevity
price_with_vat = GeneratedField(expression=F("price")*VAT, db_persist=True, output_field=DecimalField())
but if I do :
cost = Cost.objects.create(price=Decimal(10))
print(cost.price_with_vat)
# Decimal(0)
but if I do
cost_from_db = Cost.objects.get(price=Decimal(10))
print(cost_from_db.price_with_vat)
# Decimal(11.7)
This is a surprising behavior, is this expected? am I doing something wrong?
Also - I try to understand this behavior more deeply and build my mental model of those- what are the differences between "generated fields" and using the F expressions in the a queryset? My guess, with db_persist it's more like a materialized view, but what other differences exist that I might need to be aware of
maybe someone wants to do a talk on that :)