In odoo, I have 2 fields: state_id and district_id. Essentially, I want to select a state, then when selecting a district, it will only show the districts that belong to that state. I usually do it like this:
t will create a dummy field
domain_district = fields.Char(compute='_compute_domain_district')
and calculate for that field, this field will store the id of the district school that you need to display
@api.depends('state_id')
def _compute_domain_district(self):
for rec in self:
if rec.state_id:
districts = self.env['res.country.district'].sudo().search([('state_id', '=', rec.state_id.id)])
domain = [('id', 'in', districts.ids)] if districts else []
else:
domain = []
rec.domain_district = json.dumps(domain)
inside xml t just need
<field name="district_id" invisible="country_code != 'VN'" placeholder="District" domain="domain_district"
nolabel="1"/>
This method worked quite well, but I found it long and complicated because I had to create additional calculation fields, so I wanted a simpler approach than using the onchange function, I did the following:
@api.onchange('state_id', 'district_id')
def _onchange_state_id(self):
result = {}
if self.state_id:
result['domain'] = {'district_id': [('state_id', '=', self.state_id.id)]}
else:
result['domain'] = {'district_id': [('id', 'in', [])]}
return result
But this function doesn’t seem to be correct, even though I’ve selected state_id, when selecting district_id, it doesn’t filter out the correct records, it still shows all district_id, I need your help for the problem. This ?