对具有相同产品的数量行进行分组和求和

Grouping and summing quantity lines with same product

我有这个功能,它可以过滤所有选定 MO 的原始 material 行,然后创建一个显示在树视图中的报告。

但我有一个问题,同一产品可能有多个行。所以我的目标是将所有这些行分组,然后将它们与总数量显示在一行中。

有人可以帮我解决这个问题吗?

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)