Odooers论坛

欢迎!

该社区面向专业人士和我们产品和服务的爱好者。
分享和讨论最好的内容和新的营销理念,建立您的专业形象,一起成为更好的营销人员。


0

🔍 Odoo 17 : How to Search Compute Fields Without store=True in Python (Backend)?

形象
丢弃
1 答案
0
形象
odoo
最佳答案

Note: Since your example code lacks meaning, the answer may as well. This is because in the given scenario you may as well just define a related field rather than a computed one.


In general, the reason why you can not search for a non-stored field using ORM methods directly is the fact that ultimately a search (domain) is converted to an actual SQL SELECT statement - and this statement, since it's executed on the database, can only search for information actually stored in the database.
In return this means that whatever computation happens for any given computed field, would need happen on-the-fly while searching - which could pretty quickly result in poor performance.


To search for values in a computed field you can define a search method used for that field. See also 'searching on a computed field' in https://www.odoo.com/documentation/17.0/developer/reference/backend/orm.html#computed-fields.


So, in your example this would look like this:

    age = fields.Integer(string='Age')
compute_age = fields.Integer(string='Compute Age',
compute='_compute_compute_age',
search='_search_compute_age', # defines 'how' to search
store=False)

    def _search_compute_age(self, operator, value):
# According to the compute method, there is a direct link between
# 'age' and 'compute_age', thus you can search for 'age' directly.
#  In case there is a processing happening of 'age', you will have
# to reflect this in the 'value' variable and reverse the logic.
        # As an example:
# if _compute_compute_age() does something like 'compute_age = age * 10',
# you will have to, in return, search for 'compute_age / 10' as
# this is your 'age' actually stored.
        return [('age', operator, value)]

    @api.depends('age')
    def _compute_compute_age(self):
        for rec in self:
            rec.compute_age = rec.age

    def action_search_compute_age(self):
        data = self.search([('compute_age', '=', 10)])
        if data:
            _logger.info('Search Data Found: %s', data)
        else:
            _logger.info('Search Data Not Found: %s', data)


While this works, you may still reconsider your approach and whether this field really can not be stored in the database, especially since it is needed for search operations.

The heavier the computation gets, the heavier the load on the database will be every time this field is to be rendered (and this gets multiplied by the number of records shown in a list view for example).

1 备注
形象
丢弃
形象
odoo
-

Thank you so much for the detailed explanation!
Really appreciate your time and guidance! 😊