2
votes

I know I can filter Many2one fields, from python code, or even xml views, with the domain flag, but I have a slightly different scenario right now,

Consider having a model like this:

class MyModel(models.Model):
    _name = 'mymodel'

    fieldsel = fields.Selection([('sheet', 'Sheet'),('reel','Reel')], string='Printing PPT Type', 
    track_visibility='onchange', copy=False,
    help=" ")
    fieldmany = fields.Many2one('text.paper', string="Text Paper")

The text.paper model has another Selection field, which has the same values as fieldsel, however, I cannot use domain since it will filter every text.paper statically.

My issue is, that I need to filter text.paper depending on which option I choose from fieldsel, so, let's say text.paper looks something like this:

class text_paper(models.Model):
    _name = 'text.paper'

    name = fields.Char(string="Code")
    paper_type = fields.Selection([('sheet', 'Sheet'),('reel','Reel')], string="Paper Type")

I need to filter from mymodel the text.paper depending on the fieldsel field, if reel selected, filter text.paper which are reel, and if sheet selected, filter text.paper accordingly.

I hope I've explained myself.

Any ideas?

1

1 Answers

2
votes

what you need is dynamic domain for many2one you can achive this by onchange event

    class MyModel(models.Model):
        _name = 'mymodel'

        ....
        ...

        @api.onchange('fieldsel ')
        def change_domain(self):
            """change the domain of fieldmany  whenever the user changes the selected value."""
            self.fieldmany = False # may be you want to reset the value when the user changes the selected value
            if self.fieldsel : # make sure the user has selected a value
                return {'domain': {fieldmany: [('paper_type', '=', self.fieldsel)]}}
            else: # remove domain 
                return {'domain': {fieldmany: []}}