当我使用其他模型的字段时,如何使用“store = True”使计算字段成为工作?

时间:2018-04-24 13:04:24

标签: python python-2.7 odoo-8 odoo odoo-10

我在联系人树视图中有pos_order_total字段。如果store=False,则计算得很完整,但如果我做了一些POS订单则不计算store=True。那么我该如何使用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

2 个答案:

答案 0 :(得分:3)

理论

查看computed fields

的Odoo Documentatio
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

如您所见,您需要添加依赖项以触发计算方法并更新值。在这种情况下,字段valuetax属于同一模型。因此,如果您使用的是同一模型中的字段或与该模型相关的字段,则store=True将运行良好。因此,如果可能,您应该按关系连接字段。

解决方案

在您的情况下,您需要创建一个one2many字段来关联表格。检查以下代码是否适合您:

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

答案 1 :(得分:1)

这是另一种解决方案:

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(comodel_name='pos.order',
                                    inverse_name='partner_id',
                                    string='Pos Ordres')


    @api.one
    @api.depends('pos_order_ids')
    def _compute_pos_order_total(self):

        Order_id = self.env['pos.order'].search([('partner_id', '=', self.id)])

        for Order in Order_id:
            total = 0.0
            total += Order.amount_total
        self.pos_order_total = total