Search code examples
pythonpython-2.7odoo-8odooodoo-10

How to make work a computed field with "store=True" when I am using fields from other model?


I have the pos_order_total field in the contact tree view. It is calculated perfecly if store=False, but if store=True it is not calculated if I make some POS order. So how can I make this work with store=True

from odoo import api, fields, models

class ResPartner(models.Model):
    _inherit = 'res.partner'

    pos_order_total = fields.Monetary(
        string='POS Order Total',
        compute='_compute_pos_order_total',
        store=True)

    def _compute_pos_order_total(self):
        Order = self.env['pos.order']
        for partner in self:
            total = 0.0
            domain = [('partner_id', '=', partner.id)]
            for o in Order.search(domain):
                total += o.amount_total
            partner.pos_order_total = total

Solution

  • Theory

    Take a look at the Odoo Documentatio for computed fields

    total = fields.Float(compute='_compute_total')
    
    @api.multi
    @api.depends('value', 'tax')
    def _compute_total(self):
        for record in self:
            record.total = record.value + record.value * record.tax
    

    As you can see you need to add the dependencies to trigger the computed method and update the value. The fields value and tax are in the same model in this case. So if you are using fields from the same model or related to that model, the store=True is going to work well . So you should connect the fields by relations if it is possible.

    Solution

    In your case you need to create an one2many field to relate the tables. Check if the following code works for you:

    class ResPartner(models.Model):
        _inherit = 'res.partner'
    
        pos_order_total = fields.Float(
            string='POS Order Total',
            compute='_compute_pos_order_total',
            store=True
        )
    
        pos_order_ids = fields.One2many(
            string=u'POS Orders',
            comodel_name='pos.order',
            inverse_name='partner_id',
        )
    
        @api.multi
        @api.depends('pos_order_ids.amount_total')
        def _compute_pos_order_total(self):
            for partner in self:
                total = 0.0
                for order in partner.pos_order_ids:
                    total += order.amount_total
                partner.pos_order_total = total