Odoo技术问题:如何通过ID为Many2many字段设置默认值
Odoo Many2many字段设置默认选中第一条记录的方法
针对你定义的alarm_ids字段,要默认选中系统中已存在的第一条calendar.alarm记录,可以通过以下两种方式实现:
方式一:动态获取第一条记录(推荐,无需硬编码ID)
直接在字段定义中添加default参数,用lambda函数查询并返回第一条记录的ID集合:
# alarms alarm_ids = fields.Many2many( 'calendar.alarm', 'calendar_alarm_calendar_event_rel', string='Reminders', ondelete="restrict", help="Notifications sent to all attendees to remind of the meeting.", default=lambda self: self.env['calendar.alarm'].search([], limit=1).ids )
search([], limit=1)会查询所有calendar.alarm记录并取第一条,.ids将记录转为ID列表,符合Many2many字段默认值的格式要求。
方式二:硬编码固定ID(适用于ID确定且不会变更的场景)
如果你明确知道目标记录的ID(比如ID=1),可以直接用Odoo规定的三元组格式设置默认值:
# alarms alarm_ids = fields.Many2many( 'calendar.alarm', 'calendar_alarm_calendar_event_rel', string='Reminders', ondelete="restrict", help="Notifications sent to all attendees to remind of the meeting.", default=[(6, 0, [1])] )
这里的(6, 0, [ID列表])是Odoo Many2many字段默认值的标准格式:6表示替换现有记录,0为占位符,最后是要选中的记录ID数组。
注意:修改代码后需要升级对应模块,设置才会生效。
内容的提问来源于stack exchange,提问作者Wald Sin
相关产品推荐
相关产品推荐

