首页 > 解决方案 > 如何计算采购订单行中每列的平均价格?

问题描述

我想添加一个字段来计算供应商产品线的平均成本价格。在模板中,我得到了第一行的价格,但是如果我添加一个新的供应商,我会得到一个行错误

我在产品中添加了一个计算字段。从供应商处获取价格的模板表单。

@api.one
@api.depends('seller_ids.price')
def av_price(self):
    for rec in self:
        avg_price_list = [rec.seller_ids.price]
        avg_price_list= [float(x) for x in avg_price_list]
        try:
            rec.av_price = float(sum(avg_price_list) / len(avg_price_list))
        except ZeroDivisionError:
            if rec.av_price == float("inf") or self.av_price == float("-inf"):
                return float('nan')  # or x or return whatever makes sense
        pass
av_price = fields.Float(string="av price",  required=False, compute=av_price )

这是日志

 File "/home/autoparts/Developments/odoo11/odoo/odoo/models.py", line 4371, in ensure_one
raise ValueError("Expected singleton: %s" % self)
 ValueError: Expected singleton: product.supplierinfo(<odoo.models.NewId object at 0x7f0004af1ee8>, <odoo.models.NewId object at 0x7f0004af1c78>)

标签: pythonpython-3.xodoo

解决方案


错误在[rec.seller_ids.price]. seller_ids当您添加第二个条目时,将是一个包含 2 个条目的记录集。您不能直接在此类记录集上调用属性/字段,而只能在单例(只有一条记录的记录集)上调用。

所以你的方法应该更像这样:

@api.depends('seller_ids.price')
def av_price(self):
    for rec in self:
        price_list = [s.price for s in rec.seller_ids]
        if price_list:
            rec.av_price = sum(price_list) / len(price_list)
        else:
            rec.av_price = -1  # can make sense or 0

IMO 您应该将字段重命名为avg_price,因为将平均值缩写为avg. 并尝试遵守 Odoo 的指南并将方法重命名为compute_avg_priceor compute_av_price


推荐阅读