如何用值 [ODOO 12] 更新 One2many 列表

how to update One2many list with value [ODOO 12]

我添加了一个方法,在课程中对老师进行研究,然后他在院子里添加(课程有几节课,每节课一个老师) 我的问题是当我点击按钮时它没有 table 更新,他在每次点击

下面添加了另一行

这是我的代码

    teacher_ids = fields.One2many('school.teacher', 'course_id', string='Teacher')

    def get_teachers (self):
        lesson = self.env['school.lesson'].search([])

        teacher_list = []  
        for rec in lesson:
            if rec.course_id.id == self.id:
                print(rec.teacher_id.name)

                teacher_list.append([0,0,{
                                    'teacher_name':  rec.teacher_id.id,  
                                    'lesson_id': rec.id,
                                }])
        print('teacher_list',teacher_list)
        self.write({'teacher_ids' : teacher_list})
        return 

我发现

(6, 0, [IDs])          replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)

但我不知道我的方法是怎么用的

你不能在 one2many 字段中使用 (6, 0, [IDs])。因为 official document 说。

  • (4, id, _) adds an existing record of id id to the set. Can not be used on One2many.
  • (5, _, _) removes all records from the set, equivalent to using the command 3 on every record explicitly. Can not be used on One2many. Can not be used in create().

你应该用这个代替

self.teacher_ids = self.env['your_teachers_model'].search([('id', 'in', [(rec.id) for rec in lesson])])

先放

self.teacher_ids = [(6, 0, [])]

然后更新为

self.write({'teacher_ids' : teacher_list})

它将起作用:

def get_teachers (self):
    lesson = self.env['gestcal.lesson'].search([])

    teacher_list = [] 
    for rec in self.lesson_id:
        teacher_list.append([0,0,{
                                'teacher_name':  rec.teacher_id.id,  
                                }])
    print('teacher_list',teacher_list)
    self.teacher_ids = [(6, 0, [])]
    self.write({'teacher_ids' : teacher_list})
    return