forvas forvas - 7 months ago 11
Python Question

How to add and show some attributes to a many2many relationship (OpenERP7)?

This is a tricky question.

I am trying to add some fields to a many2many table. I was googling and I found that I have to create an intermediate table to stores those fields. But it is not working very well.

My example:
I created a table (training_course). A partner can join to many training_course, and a training_course is made up by many partners (So, this is a many2many relationship). I have to store the date when the partner joined the course.

So, in the partner form, I have to see the list of the courses he has joined, everyone with their dates.

My code is:

res_partner_course_rel (This is the intermediate class generated by me -with name = 'res.partner.course.rel'-)

_columns = {
'partner_id': fields.many2one('res.partner', 'Partner', ondelete='cascade'),
'course_id': fields.many2one('training.course', 'Course', ondelete='cascade'),
'date': fields.date('Joining date'),
}


res_partner

_columns = {
'courses': fields.many2many('res.partner.course.rel', id1='partner_id', id2='partner_course_rel_id', string='Courses'),
}


The problems I have are:


  • In the partners form, when I click on add a new record in the
    resultant list, I had to select the partner (which is a nosense,
    because it must be the current one).

  • The resultant list only shows a column (partner), when I would
    like to show two (course and date).



Anyone can help me a bit, please? I am trying several things but I cannot manage what I need.

Answer

If one course can have multiple dates (and not only one) then you define 3 tables (forget a many2many relationship):

partner_course_rel (.py) (you had this ok)

_columns = {
    'partner_id': fields.many2one('res.partner', 'Partner', ondelete='cascade'),
    'course_id': fields.many2one('training.course', 'Course', ondelete='cascade'),
    'date': fields.date('Joining date'),
}

_sql_constraints = [
    ('rel_unique', 'unique(partner_id, course_id, date)', 'This course already give to this company!!'),
]

training_course (.py)

_columns = {
    'name': fields.char('Name'),
    'partner_rel_ids': fields.one2many('partner_course_rel', 'course_id'),
}

res_partner (.py)

_columns = {
    'course_rel_ids': fields.one2many('partner_course_rel', 'partner_id'),
}

And in the views:

training_course (.xml)

<field name="partner_rel_ids" nolabel="1">
    <tree string="Partners" editable="bottom">
        <field name="date"/>
        <field name="partner_id"/>
    </tree>
</field>

res_partner (.xml)

<field name="course_rel_ids" nolabel="1">
    <tree string="Courses" editable="bottom">
        <field name="date"/>
        <field name="course_id"/>
    </tree>
</field>

I think this solve your problem (IF ONE COURSE CAN HAVE MULTIPLE DATES).

Comments