Odoo新手技术问询:如何实现Many2many字段依赖Many2one字段?
解决Odoo中Many2many字段依赖Many2one字段的问题
嘿,作为Odoo新手碰到这种字段联动的需求太正常了,我给你两种常用的实现方式,你可以根据自己的场景选择:
方法一:使用动态Domain(推荐,简洁高效)
这种方式直接在key_letter_id的字段定义里配置动态domain,让它自动关联gathering_id的选中值。
首先要确保你的health_administrator.key_letter模型里已经定义了关联gathering_model的字段(比如gathering_id = fields.Many2one('health_administrator.gathering_model')),这样才能基于这个字段做过滤。
然后修改你的key_letter_id字段定义:
key_letter_id = fields.Many2many( 'health_administrator.key_letter', string='Key Letters', domain="[('gathering_id', '=', gathering_id)]" )
这里的domain="[('gathering_id', '=', gathering_id)]"意思是:只有当key_letter记录的gathering_id和当前表单选中的gathering_id一致时,才会出现在可选列表里。当你切换gathering_id时,key_letter_id的选项会自动更新。
方法二:使用onchange方法(适合复杂逻辑)
如果你的过滤逻辑不是简单的匹配相等,而是需要更复杂的判断(比如根据gathering_id的其他属性过滤),那可以用onchange方法来动态更新domain:
from odoo import models, fields, api class YourModel(models.Model): _name = 'your.model.name' # 替换成你的实际模型名 _description = 'Your Model Description' gathering_id = fields.Many2one('health_administrator.gathering_model', string='Gathering') key_letter_id = fields.Many2many('health_administrator.key_letter', string='Key Letters') @api.onchange('gathering_id') def _onchange_gathering_id(self): if self.gathering_id: # 这里可以写自定义的过滤逻辑,比如根据gathering_id的状态、日期等筛选 return { 'domain': { 'key_letter_id': [('gathering_id', '=', self.gathering_id.id)] } } else: # 如果没有选中gathering_id,清空可选列表(或者改成[()]显示所有) return { 'domain': {'key_letter_id': []} }
这个方法会在gathering_id的值发生变化时触发,动态修改key_letter_id的可选范围,灵活性更高。
注意事项
- 一定要确认
health_administrator.key_letter模型中存在关联gathering_model的字段,否则过滤条件会失效。 - 如果你的视图里给
key_letter_id设置了固定domain,记得要和这里的动态逻辑兼容,避免冲突。
内容的提问来源于stack exchange,提问作者Marcel Brou
相关产品推荐
相关产品推荐

