Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

django db generated model fields - question and what appears to be a surprising behavior

7 views
Skip to first unread message

alonn

unread,
Aug 23, 2024, 12:55:12 PM8/23/24
to PyWeb-IL
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 :) 

Meir Kriheli

unread,
Aug 30, 2024, 2:48:58 AM8/30/24
to pywe...@googlegroups.com
It's a bit like materialized views (or views in general): views over table, generated over column.

I recommended reading the PG docs on it:

Regarding Django's behavior, I would check the table schema, and log the executed query upon INSERT (specially the RETURNING part). That may provide a good insight.

Cheers

--
You received this message because you are subscribed to the Google Groups "PyWeb-IL" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyweb-il+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pyweb-il/2dbd56e7-48e2-4f05-90f3-bd29c1b59d42n%40googlegroups.com.


--
Reply all
Reply to author
Forward
0 new messages