Odoo: how to set default field for many2many field by id?

Viewed 171

i want to set default value in many2many field for example: field view

that field in models.py:

# 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.")

also it is default values created by system, and i want first variant by default: existed records with id`s

i know that i can set it by id, but dont know how.

2 Answers

You can use Command to set X2many field values.

From the documentation:

Via Python, we encourage developers craft new commands via the various functions of this namespace. We also encourage developers to use the command identifier constant names when comparing the 1st element of existing commands.

Example:

from odoo import Command, models, fields

        
class CalendarEvent(models.Model):
    _inherit = 'calendar.event'
    
    alarm_ids = fields.Many2many(default=lambda self: [Command.link(self.env.ref('calendar.alarm_notif_1').id)])

i just watch in postgres, there is no id`s like in xml screenshots, i just take id of a record and find some documentation. next example works: enter image description here

Related