In my odoo module I have a internal_division model and a cover model. Every internal divisiom has a cover (Many2One field) and a cover can be a forest ('is_forest' boolean field). Internal division also has a with_forest_cover boolean field. Every time the 'with_forest_cover' changes to True, the cover_id field must change its domain to those having 'is_forest'=True, and the other way around. I was trying to do it using:
cover_id = fields.Many2one('cusaf.cover', string='Cobertura',domain="[('is_forest', '=', with_forest_cover)]")
But for some reson this is only working when creating a new internal_division. When I edit an existing internal division and select / deselect the 'with_forest_cover' check box, the cover_id field is not changing its domain. This is only happening when editing an existed internal division. Why is this happening. I am working with odoo v14 Here is my code
class InternalDivision(models.Model):
_name = 'cusaf.internal_division'
_description = 'División interna'
_inherit = ['mail.thread', 'mail.activity.mixin']
name = fields.Char(string='Identificador externo', required=True)
_sql_constraints = [
('name_uniq', 'unique (name)',
"Error: Ya existe una división interna con el mismo identificador externo") ]
with_forest_cover = fields.Boolean(string='Área con cobertura de bosques naturales', default=False)
cover_id = fields.Many2one('cusaf.cover', string='Cobertura',domain="[('is_forest', '=', with_forest_cover)]")
cover_other = fields.Char(string='Otra cobertura')
cover_name = fields.Char(string='', related="cover_id.name")
@api.onchange('with_forest_cover')
def _with_forest_cover_onchange(self):
self.cover_id=None
class Cover(models.Model):
_name = 'cusaf.cover'
_description = 'Tipo de cobertura'
name = fields.Char(string='Nombre', required=True)
_sql_constraints = [
('name_uniq', 'unique (name)',
"Error: Ya existe un tipo de cobertura con el mismo nombre")
]
description = fields.Text(string='Descripción')
is_forest = fields.Boolean(string='Es bosque')
You won't be able to access to the with_forest_cover
value inside cover_id
domain, 'cause your class is instantiated before the client, in that time there aren't values. You have 1 easy, 1 intermediate and 1 elevated(not worth the effort) solutions:
Important: Delete domain for cover_id
in.py
Easy: Domain in XML. Be sure with_forest_cover
is declared in the XML.
<field name="cover_id" domain="[('is_forest', '=', with_forest_cover)]"/>
Intermediate: take advantage of your with_forest_cover
onchange to retrieve a domain for cover_id
dynamically
@api.onchange('with_forest_cover')
def _with_forest_cover_onchange(self):
return {
'value': {'cover_id': False},
'domain': {'cover_id': [('is_forest', '=', self.with_forest_cover)]}
}
I hope this could be helpful for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.