from odoo import fields, models, api class Elective(models.Model): _name = 'yuthon.school.elective' _description = '选修课' name = fields.Char( string='选修课名称', required=True, help='如:Odoo 工作流开发、OWL 前端框架入门', ) description = fields.Text( string='课程简介', ) teacher_id = fields.Many2one( 'yuthon.school.teacher', string='授课教师', ) student_ids = fields.Many2many( 'yuthon.school.student', 'yuthon_elective_student_rel', 'elective_id', 'student_id', string='选课学生', help='选择选修该课程的学生(Many2many 关系演示)', ) student_count = fields.Integer( string='选课人数', compute='_compute_student_count', store=True, ) active = fields.Boolean( string='启用', default=True, ) @api.depends('student_ids') def _compute_student_count(self): for record in self: record.student_count = len(record.student_ids)