Before we discuss how to use the computed fields in the search domain, we need to first understand what Odoo’s computed fields are and look into some of their important characteristics…
So what exactly is a computed field? In Odoo, a computed field is like a regular field except it is declared with an additional argument named ‘compute’. These fields are used when the values of the field can be calculated or computed from other fields using a function. The values of the computed fields are calculated dynamically at the runtime. One of the important characteristics of computed fields is that by default these fields are not stored in the database. Since they are not stored in the database, computed fields are not searchable, i.e., they cannot be used in the domain for search or filter unless we add some other functionalities to the computed field. Another characteristic of computed fields is that these fields are read-only by default. To allow editing options for the computed fields, the ‘inverse’ parameter can be used in the field declaration.
There are 2 methods to store a computed field in Odoo –
- By adding ‘store = True’ in the field declaration.
- By adding a ‘search function’ in the field declaration.
We will now look into the above methods and then look into their use in the search domain.
CASE I – Adding ‘store=True’
The image below shows the declaration of a regular date field and a computed field with the attribute ‘store=True’.
The image below shows the computer function written for the above field.
If the value of the computed field depends on another field, then @api.depends decorator can be used in the compute function, to trigger the computation whenever the dependent field is changed or changed.
Request Your Free Quote
CASE II – Adding search function
The image below shows the declaration of a regular date field and a computed field with a ‘search’ parameter.
The image below shows the computer function and the search function. Three parameters are passed in the search function self, operator, and value.
The search method defined is initialized when processing domains prior to doing an actual search on the model. The search method must return a domain equivalent to the condition – field, operator, and value.
After declaring the computed field in either of the two above methods, the computed fields can now be used in the search or filter domain.
EXAMPLE – The above-computed field,i.e., ‘is_expired’ can be used in the search domain.
In XML, we can define a search record using the “is_expired” field as shown below.
Thus, by using any of the above methods to store computed fields in the database, these fields can be used in the search or filter domain just like a regular field.