Search code examples
pythonodoo-12

Odoo: Values of Many2many with dynamic domain aren't getting saved


I am trying to dynamically change the values of a many2many field products_ids based on multiple onchange functions of other fields (e.g. brand_id and origin_id). So far everything is working great and it does show the expected values, but once i hit the save button the values of the many2many field disappear

enter image description here

class CustomModifyPrice(models.Model):
    brand_id = fields.Many2many(comodel_name="custom.brand", string="Brand", required=False, )
    origin_id = fields.Many2many(comodel_name="custom.country", string="Origin", required=False, )
    product_ids = fields.Many2many(comodel_name="custom.product", string="Products", readonly=True, )
    search_terms = {}
    product_ids_list = []

    @api.onchange('brand_id')
    def onchange_change_brand(self):
        for rec in self:
            product_brands = []
            for prod_brand in rec.brand_id:
                product_brands.append(prod_brand.id)
            rec.search_terms["product_brands"] = product_brands
            rec.get_products()

    @api.onchange('origin_id')
    def onchange_change_origin(self):
        for rec in self:
            product_origins = []
            for prod_origin in rec.origin_id:
                product_origins.append(prod_origin.id)
            rec.search_terms["product_origins"] = product_origins
            rec.get_products()

    def get_products(self):
        domain = []
        self.product_ids_list = []
        if 'product_brands' in self.search_terms:
            product_brands = self.search_terms['product_brands']
            if product_brands:
                tuple1 = ('brand_id', 'in', product_brands)
                domain.append(tuple1)

        if 'product_origins' in self.search_terms:
            product_origins = self.search_terms['product_origins']
            if product_origins:
                tuple1 = ('country_id', 'in', product_origins)
                domain.append(tuple1)

        if domain:
            products = self.env['custom.product'].search(domain)
            if products.ids:
                for prod in products:
                    self.product_ids_list.append(prod.id)
            self.product_ids = [(6, False, self.product_ids_list)]

Solution

  • Make sure force_save="1" is placed as an attribute in your field (xml file)