Many2many relation in Odoo 10 (python)

Lee Dat picture Lee Dat · Feb 14, 2017 · Viewed 10k times · Source

I have to create a STudent Management module by Odoo 10.0 in windows. So I'd like to know exactly how to establish a "many2many" relation in Odoo (not Openerp). I have searched a lot of solutions on the Internet, but I don't understand clearly them : enter image description here

For example, there are 2 classes (Student and Course) following with their attributes :

 class Student(models.Model):
      _name = "management.student"
      IdStudent = fields.Integer() #primary key
      Name = fields.Char()
      Gender = fields.Char()
      Address = fields.Char()

 class Course(models.Model):
      _name = "management.course"
      IdCourse = fields.Integer() #primary key
      course = fields.Char()
      credit = fields.Integer()
      professor = fields.Char()

Thanks a lot for your help !

Answer

Phillip Stack picture Phillip Stack · Feb 14, 2017

Many2many relations in Odoo are best described as many records of one model can be linked to many records of another model. To use your example many classes can have many students and students can have many classes, hence many2many. As apposed to many2one such as an apple can only have only one tree or one2many one tree can have many apples.

To define a many2many relationship for Courses and Students you can create a field on the course like this. (taken from the docs)

attendee_ids = fields.Many2many('management.student', string="Attendees")

In this case because you have not specified the optional arguments column1,column2 Odoo will create a new relation table linking the two models. The table will have a name like this.

management_course_management_student_rel

However you can specify your own table name and columns for your relation table.

attendee_ids = fields.Many2many('management.student',relation='your_table_name', column1='course_id',column2='student_id', string="Attendees")

This would produce a table called your_table_name with two columns course_id and student_id

To determine what students are in a course Odoo would execute a query

SELECT student_id from your_table_name where course_id = x

And the opposite to find what courses a student is taking.