You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:36:24