如何在odoo中的搜索orm中获取计算字段值

How to get computed field value in search orm in odoo

我在 odoo 10 中用计算方法定义了一个 computed field,现在我想在 search orm 中获取它的值,但它的值仍然是 False,当我尝试 store=True 它的值没有被改变。 如果有人有解决方案请告诉我,我将不胜感激。 我的代码是:

balance_amount = fields.Float(string="Balance Amount", compute='_compute_loan_amount')

@api.one
def _compute_loan_amount(self):
    total_paid = 0.0
    for loan in self:
        for line in loan.loan_lines:
            if line.paid:
                total_paid += line.amount
        balance_amount = loan.loan_amount - total_paid
        self.total_amount = loan.loan_amount
        self.balance_amount = balance_amount
        self.total_paid_amount = total_paid

当我使用下面的search_count时:

loan_count = self.env['hr.loan'].search_count([('employee_id', '=', values['employee_id']), ('state', '=', 'approve'),
                                                   ('balance_amount', '!=', 0)])

即使balance_amount等于Zero

也总是得到计数值

有些事情你必须在这里做。

  1. 定义重新计算依赖项并使用 @api.multi 和 for 循环覆盖 self 或使用 api.one 并跳过 for 循环。如果我理解你的计算方法是正确的:
@api.multi
@api.depends('loan_lines.paid', 'loan_lines.amount', 'loan_amount')
def _compute_loan_amount(self):
    for loan in self:
        total_paid = 0.0
        for line in loan.loan_lines:
            if line.paid:
                total_paid += line.amount
        balance_amount = loan.loan_amount - total_paid
        loan.total_amount = loan.loan_amount  # ???
        loan.balance_amount = balance_amount
        loan.total_paid_amount = total_paid
  1. 尝试使用浮点舍入,例如2 位小数,因为浮点数可以产生类似 0.000000000000000002 的值,这会破坏您的搜索。

  2. 您要么必须存储该值,要么必须定义一个 search 方法。第二种方法更难(根据我的经验)。