odoo - 对具有相同产品的数量行进行分组和求和
问题描述
我有这个功能,它过滤所有选定的 MO 原材料行,然后创建一个显示在树视图中的报告。
但是我有一个问题,同一产品可以有分配线。所以我的目标是将所有这些行分组并显示它们,然后在一行中显示总和。
有人可以帮我弄这个吗?
class RawMaterialReport(models.Model):
_name = 'raw.material.report'
_description = 'Raw Material Report'
product_id = fields.Many2one('product.product', string='Product', required=False)
code = fields.Char(string='Code', required=True, readonly=True)
total_qty = fields.Float(string='Total Qty', digits=(6, 2), readonly=True)
virtual_qty = fields.Float(string='Forcasted Qty', digits=(6, 2), readonly=True)
origin = fields.Char(string='Origin', required=True, readonly=True)
production_id = fields.Many2one('mrp.production')
@api.multi
def open_raw_materials(self):
self.search([]).unlink()
mrp_productions = self._context.get('active_ids')
mrp_production = self.env['mrp.production'].browse(mrp_productions)
products_without_default_code = mrp_production.mapped('move_raw_ids').filtered(
lambda x: not x.product_id.default_code
)
raws = mrp_production.mapped('move_raw_ids').sorted(
key=lambda r: r.product_id.default_code
)
for r in raws:
vals = {
'product_id': r.product_id.id,
'code': r.product_id.default_code,
'total_qty': r.product_id.qty_available,
'virtual_qty': r.product_id.virtual_available,
'origin': r.reference,
'production_id': r.raw_material_production_id.id,
}
self.create(vals)
解决方案
与其直接创建记录,不如将它们保存在按产品 ID 分组的字典中,当您发现所有准备好的产品都有记录时,只需将其数量相加即可。
@api.multi
def open_raw_materials(self):
self.search([]).unlink()
mrp_productions = self._context.get('active_ids')
mrp_production = self.env['mrp.production'].browse(mrp_productions)
products_without_default_code = mrp_production.mapped('move_raw_ids').filtered(
lambda x: not x.product_id.default_code
)
raws = mrp_production.mapped('move_raw_ids').sorted(
key=lambda r: r.product_id.default_code
)
# to group by product
recs = {}
for r in raws:
product_id = self.product_id.id
if product_id in recs:
# here just update the quantities or any other fields you want to sum
recs[product_id]['product_uom_qty'] += self.product_id.product_uom_qty
else:
# keep the record in recs
recs[product_id] = {
'product_id': r.product_id.id,
'code': r.product_id.default_code,
'total_qty': r.product_id.product_uom_qty,
'virtual_qty': r.product_id.virtual_available,
'origin': r.reference,
'production_id': r.raw_material_production_id.id,
}
for vals in recs.values():
# create records this will create a record by product
self.create(vals)
推荐阅读
- django - Django 新创建的实例 - DateTime 字段类型为“str”
- php - 具有两个字段的数组上的 Laravel 验证存在于数据库行上
- symfony4 - 选中一个按钮单选时,显示 dateTypefrom,如果不是从 TextType 获取值
- android - 如何在片段中按钮的可见性上使用 onSaveInstanceState?
- python - 将关键字插入 .inp 文件的 Abaqus Python 命令
- reactjs - 使用 React 展开/折叠标题列表
- reactjs - 行动/调度不更新商店
- linux - 使用 MDEV-17458 将 galera-cluster 更新到 10.3.15
- firebase - 如何在 Vue.js 应用程序中配置 firebase cdn / 缓存?
- python-3.x - 使用 python psycopg2 在 PostgreSQL 数据库中插入嵌套 json 数据(某些键不存在)时出现问题