In Odoo, it's common to use One2many fields with inline "Add a line" functionality. A frequently requested feature is to auto-increment a numeric field, such as a sequence number, every time the user adds a new line.
This guide demonstrates how to auto-increment a field (e.g., sequence
) in a One2many line when clicking “Add a line” in the Odoo form view.
Use Case
You have a model indoor.dashboard.device
with a field called sequence
. You want this field to increase by 1 each time a new line is added in the One2many list.
Parent Model
class IndoorDashboard(models.Model):
_name = 'indoor.dashboard'
_description = 'Indoor Dashboard Management'
name = fields.Char(string='Name', required=True, copy=False, readonly=True,
default=lambda self: self.env['ir.sequence'].next_by_code('indoor.dashboard.sequence') or 'New')
title = fields.Char(string='Title')
item_date = fields.Datetime(string='Date', default=fields.Datetime.now)
author = fields.Char(string='Author')
location = fields.Char(string='Location')
remark_header = fields.Text(string='Remark')
state = fields.Selection([
('draft', 'Draft'),
('confirmed', 'Confirmed'),
('done', 'Done'),
], string='Status', default='draft', readonly=True, tracking=True)
device_ids = fields.One2many('indoor.dashboard.device', 'dashboard_id', string='Devices')
Child Model
class IndoorDashboardDeviceLine(models.Model):
_name = 'indoor.dashboard.device'
_description = 'Indoor Dashboard Device'
dashboard_id = fields.Many2one('indoor.dashboard', string='Dashboard', required=True, ondelete='cascade')
sequence = fields.Integer(string='No.')
name = fields.Char("Device")
code = fields.Char("Node#")
device_type = fields.Selection([('temperature', 'Temperature'), ('humidity', 'Humidity')], default='temperature', string="Type")
url = fields.Char("Url")
remark = fields.Char("Remark")
@api.onchange('dashboard_id')
def _onchange_dashboard_id_sequence(self):
if self.dashboard_id: # When Click Add a Line on Form View
existing_lines = self.dashboard_id.device_ids.filtered(lambda l: l != self)
max_sequence = max(existing_lines.mapped('sequence') or [0])
self.sequence = max_sequence + 1
Result
The solution is to use @api.onchange('dashboard_id')
in the child model.
When you click Add a Line, the No.
column (sequence) will automatically increment based on the existing lines.
Reply