In Odoo, when working with Many2one
fields, the label shown in dropdowns (autocomplete fields) is determined by the default name
field. However, sometimes you may want to display more context in that dropdown — like combining the record’s name with another field (e.g., device type or custom label).
how to use a computed display_name
field to override what appears in the Many2one selection dropdown.
Step 1: Define Your Model and Fields
Let’s assume I'am building a model to represent IoT devices or nodes.
from odoo import models, fields, api
class DeviceNode(models.Model):
_name = 'device.node'
_description = 'Device Node'
name = fields.Char(
string='Code',
required=True,
readonly=True,
copy=False,
default=lambda self: self.env['ir.sequence'].next_by_code('device.node.sequence') or 'New'
)
item_date = fields.Datetime(string='Date', default=fields.Datetime.now)
author = fields.Char(string='Author')
device_type = fields.Selection([
('cctv', 'CCTV'),
('temperature', 'Temperature'),
('humidity', 'Humidity'),
('stack_light', 'Stack Light'),
], default='temperature', string="Type")
device_name = fields.Char("Device Name")
remark = fields.Char("Remark")
display_name = fields.Char(
string='Display Name',
compute='_compute_display_name',
index =True,
store=True,
)
@api.depends('name', 'device_name')
def _compute_display_name(self):
for record in self:
if record.device_name:
record.display_name = f"{record.name} - {record.device_name}"
else:
record.display_name = record.name
Step 2: Use It in Other Models
Here’s an example of how you can reference device.node
in another model:
class MyModel(models.Model):
_name = 'my.model'
device_id = fields.Many2one('device.node', string='Device')
Now, when users open the dropdown for device_id
, they will see entries like:
DN0005 - Sensor A
DN0006 - Main Camera
Add an Index for Performance
If your dataset is large and you frequently search by display_name
, consider adding:
_sql_constraints = [
('name_uniq', 'unique(name)', 'Name must be unique!')
]
Reply