Computed fields
Fields can have their values automatically calculated by a function, instead of simply reading a database stored value. A computed field is declared just like a regular field, but has the additional compute
argument to define the function used for its computation.
In most cases, computed fields involve writing some business logic. So, to take full advantage of this feature, we need to learn the topics explained in Chapter 8, Business Logic - Supporting Business Processes. We can still explain computed fields here, but will keep the business logic as simple as possible.
Let's work on an example. Books have a publisher. We would like to have the the publisher's country in book form.
For this, we will use a computed field, based on the publisher_id
, which will take its value from the publisher's country_id
field.
We should edit the book model in the library_app/models/library_book.py
file to add the following:
# class Book(models.Model):
publisher_country_id = fields.Many2one...