Search code examples
odooodoo-8odoo-9

Update fields with different number of values


In res.partner model I have a field

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

and in sale.order

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

Partner can have more than one price list so my goal is to add the first pricelist to the pricelist_id field and other pricelists to alternative_pricelist_ids. The things are that how I wrote code is not really good, as you can see I will get an error if there are more than 4 pricelists. So how can I avoid it and write it another way?

   @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)

Solution

  • Try this :

    @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)]