Search code examples
pythonodooodoo-12

How to filter one Many2one field based on value of another in odoo


I have these fields in my model:

seller = fields.Many2one('res.partner', string="Select Seller",domain="[('supplier','=',True)]")
products= fields.Many2one('product.template', string="Select Product" )

Now, i need to filter the second field as the user chooses a seller(first field) How do i set a domain onchange.

I am trying to do something like,

@api.onchange('seller')
    def onchange_field_seller(self):
        res = {}
        if self.seller:
            # return {'domain':{'product':[//what do i add here//]}}
        return res

I am using a many2many field to create the products in the seller creating form.

product_details = fields.Many2many('product.template',string="Products")

(Please note that the form with this field is different from the one in the question above). I am trying to get only those product entries that were created when i created the seller entry.Im really confused, how do i accomplish this?


Solution

  • In your case you can't use a "dynamic" domain but more of a pre-defined domain on product IDs.

    @api.onchange('seller')
    def onchange_field_seller(self):
        if self.seller:
            # filter products by seller
            product_ids = self.seller.product_details.ids
            return {'domain': {'product': [('id', 'in', product_ids)]}}
        else:
            # filter all products -> remove domain
            return {'domain': {'product': []}}