pythonpython-3.xdjangodatabasedjango-models

Django 5.0: How GeneratedField actually works?


I've read the Django documentation about the new models.GeneratedField, but I don't quite understand how it works inside a database.


Can someone explain this?


Solution

  • As it's said in the paragraph under this link, it uses GENERATED ALWAYS SQL syntax which is supported by your DBMS (e. g. Postresql). You can use it by passing expression into it. So it will generate that field and store it in DB, so you don't need to 'apply' that expression when you select that row, instead you just use that column (which btw would be already ready to use).

    For example you have table for Money Tansfer you have transaction amount (for example I want send my 100 USD) and setltement amount (I'm going to send it to the EUR account), you can save both amounts only and when you'll need the exchabge rate you can just calculate it or you can ust store it as generated field as one of them divided by another