Tuesday, October 18, 2022

domain many2many fields in odoo 14


In this blog we will explain how to set domain many2many fields in Odoo 14

So let us say that we have four models (restaurants model, food category model, food model and orders model) the restaurant contains many categories, the category can contain many foods , as bellow 

 

class restaurants(models.Model):
    _name = "res.restaurants"
    category_ids = fields.Many2many('res.category', string="categories")
 

 

class Foods(models.Model):
    _name = "res.foods"
    category_id = fields.Many2one('res.category', string="Category")


class Orders(models.Model):
    _name = "res.orders"
    restaurant_id = fields.Many2one('res.restaurants', string="Restaurant")
    foods_ids = fields.Many2many('res.foods', string="Foods")


To create order the user must select the restaurant then select foods , but the system must show the food with category_id in  order.restaurant_id.category_ids

So we can do it by creating function in order model called on-change restaurant_id and this function will set the domain for foods , just as bellow

 

@api.onchange('restaurant_id')
    def _set_foods_domain(self):
        res = {}
        if self.restaurant_id:
            ids_lis = []
    
        food_ids = self.env['res.foods'].search([])
            for food_id in self.category_ids:
                if food_id.id in self.restaurant_id.mapped("category_ids").ids:
                    ids_lis.append(food_id.id)
            res['domain'] = {'food_ids': [('id', 'in', ids_lis)]}
        return res

No comments:

Post a Comment

Odoo Invoice Qr code issues

There are two main issues must of us facing with the QR code in Odoo invoice & these issues are 1/ QR code displayed as broken image w...