将 many2many 字段显示为 many2one

Show a many2many field as a many2one

我有一个 many2many 字段,在特定视图中我需要将其显示为 many2one,或者模仿 many2one 字段的行为(限制只能添加一条记录,如果用户 select另一条记录,之前 selected 的记录将被删除)。在我声明的视图中:

<field name="employee_ids" widget="many2one" />

但它给了我以下错误:

TypeError: 'int' object is not iterable

有什么办法可以实现吗?

我认为你可以强制用户 select 只有一条记录 使用 onchange 装饰器:

@api.onchange('employee_ids')
def force_one_selection(self):
    """Force the user to select only one record"""
    if self.employee_ids and len(self.employee_ids) > 1:
        # user has added a new record
        self.employee_ids = [(6, 0, self.employee_ids[0].id)] # you can change the index to 1
        # and you can return a warning here to tell the user that he should not select more than 
        # one record