Jorge
Jorge

Reputation: 61

Odoo12ce domain problems with self and Many2oe field

I am currently developing an odoo12ce module which must contains a table with dogs registers and its father and mother of the dogs (something like a purebred). In the field father_code I want to get just the male dogs and the ones who live in the same city.

get_domain_male(self):
  return [('gender', '=', 'male'), ('city', '=', self.city)]

father_code = fields.Many2one('asc.dog', string="Fathers code", domain = get_domain_male)

asc.dog is the same model, it means that the model is auto-referenced.

When I run the snippet, the city is already set and the field does not show anything, because self is not recognized as expected. When I print it, it is just False and the code run before I enter to the form view.

What could be wrong with the code and there is another way to filter it?? Thanks in advance for your help.

Upvotes: 2

Views: 433

Answers (2)

arryph
arryph

Reputation: 2825

From Odoo documentation

domain – an optional domain to set on candidate values on the client side (domain or string)

So, basically you can set domain as a string or list of tuples, in this case you can use string to set domain like this

father_code = fields.Many2one('asc.dog', string="Fathers code", 
  domain ="[('gender', '=', 'male'), ('city', '=', city)]")

So it will take city value from client side or view, and filter asc.dog records accordingly. Of course, to get values from client side, city field must exist in view or it will generate error the field not found in the view.

Optionally, instead of setting domain in Field definition, you can also setup domain in view definition.

<field name='city' />
<field name='father_code' domain="[('gender','=','male'),('city','=',city)]" />

Only difference is if you do it in the field definition, every view consisting father_code will always have this domain automatically set, but you must include city, visible or invisible.

Upvotes: 2

Eric
Eric

Reputation: 1126

Here we use an onchange field so that anytime the father field is changed the dog field is filtered.

It is almost always important to loop through records to avoid singleton and related issues.

@ api.onchange('father_code')
    def _onchange_father_code_filter_dog(self):
        for rec in self:
            return {'domain':
                    {'dog_field': [('gender', '=', 'male'), ('city', '=', rec.city)]}}

Upvotes: 1

Related Questions