更新具有不同数量值的字段

Update fields with different number of values

在 res.partner 模型中我有一个字段

property_product_pricelist = fields.Many2many('product.pricelist')

并在 sale.order

alternative_pricelist_ids = fields.Many2many(
        'product.pricelist')

合作伙伴可以有多个价目表,因此我的目标是将第一个价目表添加到 pricelist_id 字段,并将其他价目表添加到 alternative_pricelist_ids。问题是我编写代码的方式并不是很好,如您所见,如果价目表超过 4 个,我将收到错误消息。那怎么避免,换个方式写呢?

   @api.multi
    @api.onchange('partner_id')
    def onchange_partner_id(self):
        super(SaleOrder,self).onchange_partner_id()
        values = { 'pricelist_id': self.partner_id.property_product_pricelist[0] and self.partner_id.property_product_pricelist.id[0] or False,
                   'alternative_pricelist_ids': self.partner_id.property_product_pricelist[1] and self.partner_id.property_product_pricelist[2] and self.partner_id.property_product_pricelist[3] or False,
}
    self.update(values)

试试这个:

@api.multi
@api.onchange('partner_id')
def onchange_partner_id(self):
    super(SaleOrder, self).onchange_partner_()
    for record in self:
        pricelist_id = False
        alternative_ids = []
        for pricelist in record.partner_id.property_product_pricelist:
            if not pricelist_id:
                pricelist_id = pricelist.id
            else:
                alternative_ids.append(pricelist.id)
        record.pricelist_id = pricelist_id
        record.alternative_pricelist_ids = [(6, 0, alternative_ids)]