python - 如何计算采购订单行中每列的平均价格?
问题描述
我想添加一个字段来计算供应商产品线的平均成本价格。在模板中,我得到了第一行的价格,但是如果我添加一个新的供应商,我会得到一个行错误
我在产品中添加了一个计算字段。从供应商处获取价格的模板表单。
@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>)
解决方案
错误在[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_price
or compute_av_price
。
推荐阅读
- swift - 如何在知道所有任务何时完成的同时异步初始化 firebase firestore 侦听器?
- javascript - 将 Python dict 转换为 Javascript 对象并访问键和值
- ajax - 如何使用 ajax 和表单数据将验证码提交给控制器
- javascript - 想要从 React Native CookieManager.clearAll() 中的 webView 清除缓存;在 iOS 中不工作
- android - 带有 Jetpack 导航组件的自定义工具栏
- python-3.x - 为什么将 P,D,Q 项考虑到周期为 0 的 SARIMAX 模型中?
- c# - 从实体框架查询返回的两个 List<> 对象的外连接
- ios - 如何快速将灰度图像转换为二进制图像?
- json - 如何解决 Firefox 上 React.js 中的“this.props.items is undefined”?
- rust - 将所有权转移到 std::io::Chain