Adding computed fields to a model
We may want to create a field that depends on the values of other fields in the same record or in related records. For instance, we can calculate the total amount by multiplying a unit price by a quantity. In Odoo models, we can use computed fields to do this.
To demonstrate how computed fields work, we will add one to the Hostel Room model that computes the availability of rooms based on student occupancy.
We can also make computed fields editable and searchable. We will show you how to do this in our example as well.
Getting ready
We will continue using the my_hostel
add-on module from the previous recipe.
How to do it...
We will modify the models/hostel_room.py
code file to include a new field and the methods that implement its logic:
- A computed field’s value usually relies on the values of other fields in the same record. ORM requires the developer to declare those dependencies on the
compute
method using thedepends...