Odoo 10中如何在Search ORM中获取计算字段值?值异常求助
Hey, let's work through this issue step by step. There are a couple of critical problems in your code that are making balance_amount stay False or fail to update when you set store=True:
1. You're not assigning a value to balance_amount in your compute method
Looking at your code snippet, you calculate total_paid but never actually assign a result to balance_amount! That's why it's always False—Odoo has no value to store or return. You need to add the final calculation line based on your business logic. For example, if balance is the loan principal minus total paid:
@api.multi @api.depends('loan_lines.paid', 'loan_lines.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 # Replace with your actual balance calculation logic loan.balance_amount = loan.principal - total_paid
2. Incorrect decorator usage & missing dependencies for store=True
- The
@api.onedecorator in Odoo 10 converts the recordset to a single record, so looping overselfis redundant and error-prone. Switch to@api.multipaired with@api.dependsinstead—it's cleaner for handling multiple records. - When you set
store=True, Odoo needs to know which fields trigger a recalculation. You must define these dependencies with thedependsparameter on the field, otherwise it'll never update the stored value.
Update your field definition like this:
balance_amount = fields.Float( string="Balance Amount", compute='_compute_loan_amount', store=True, depends=['loan_lines.paid', 'loan_lines.amount', 'principal'] # Add all fields your calculation relies on )
3. Making the field accessible to Search ORM
- If you use
store=True, the field value is saved to the database, so you can query it with Search ORM just like any regular field (e.g.,self.env['your.loan.model'].search([('balance_amount', '>', 0)])). - If you don't want to store the field (skip
store=True), you'll need to define a customsearchmethod to handle queries, since Odoo can't search on non-stored computed fields directly. Here's a quick example (adjust to your logic):
balance_amount = fields.Float( string="Balance Amount", compute='_compute_loan_amount', search='_search_balance_amount' ) def _search_balance_amount(self, operator, value): # Example logic: Translate balance query to principal vs total paid return [ ('principal', operator, value + sum( self.env['loan.line'].search([('loan_id', '=', self.id), ('paid', True)]).mapped('amount') )) ]
That said, using store=True is the simpler, more reliable approach for searchability.
Quick Validation Steps
- After updating your code, upgrade your module and check if the
balance_amountcolumn exists in your loan model's database table. - Edit a loan record, mark a line as paid, save it, and verify
balance_amountupdates correctly. - Test your Search ORM query to confirm it returns the right records.
内容的提问来源于stack exchange,提问作者M Tahir Noor
相关产品推荐
相关产品推荐

