Mohamed Fouad
Mohamed Fouad

Reputation: 526

odoo domain filter many2many?

i'am added a car field in product template which related to the car model that contains all cars, also i'am work in multi compny, and i'am also added a many2many relation with car model, all i need is to filter the cars in product template and display all cars that i have been assign in the company

this is my code

class cars(models.Model):
_name = 'cars'

name = fields.Char( string="Car",translate=True , required=True, ondelete='restrict')

class autopartscompany(models.Model):
_inherit = 'res.company'

car_ids = fields.Many2many(comodel_name="cars",string="Cars" )


class autopart(models.Model):
_inherit = 'product.template'

car = fields.Many2one(comodel_name="cars", store=True, string="Car", ondelete='restrict', required=False, domain="[('name','=', self.company_id.car_ids )]")

can any one help me how to define the domain filter correctly because that one give me error Error: NameError: name 'self' is not defined

Upvotes: 3

Views: 5326

Answers (2)

Mohamed Fouad
Mohamed Fouad

Reputation: 526

this the best solution to solve it

def _get_cars_domain(self):
    print (self.company_id.car_ids)
    return [('id', 'in', self.env.user.company_id.car_ids.ids)]

car = fields.Many2one(comodel_name="cars", store=True, string="Car", ondelete='restrict', required=False,domain=_get_cars_domain)

Upvotes: 3

Charif DZ
Charif DZ

Reputation: 14721

To set a dynamic domain based on another field specially a many2many field that can hold a lot of record, use onchange I think is the best way:

class autopart(models.Model):
    _inherit = 'product.template'

    car = fields.Many2one(comodel_name="cars", store=True, string="Car", ondelete='restrict', required=False)

    # add the field itself to onchange to trigger this method in edit mode too
    @api.onchange('company_id', 'car') 
    def onchange_company(self):
        domain = []
        if self.company_id:
            domain.append(('id', 'in', self.company_id.car_ids.ids))
        return {'domain': {'car': domain}

Upvotes: 1

Related Questions