Skip to Content
Menu
This question has been flagged

I'm trying to use a many2many relation between companies and contacts.

Is there a way to use parent_id as many2many or when you create a many2many relation, how can you see on the "companies side" when you add them in contacts?


thx

Avatar
Discard
Best Answer

Hi,

it is better to avoid using the standard field parent_id which is of the many2one type. There is logic which relies upon that, and you would spent quite much time to recover it.

It is better to introduce 2 new fields of many2many:

contact_m2m_ids = fields.Many2many(
    "res.partner",
    "rel_table",
    "direct_rel_id",
    "back_rel_id",
    string="Contacts"
)
parents_m2m_ids = fields.Many2many(
    "res.partner",
    "rel_table",
    "back_rel_id",
    "direct_rel_id",   
    string="Companies"
)

Basically, many2many fields are based on a intermediary table, which might be used for both direct and backward relation. In the example it is the table 'rel_table', which has 2 columns 'back_rel_id' & 'direct_rel_id'. It is possible to avoid defining 'rel_table': but if you have 2 relational fields for the same model, it will not work. For more info look at: https://www.odoo.com/documentation/10.0/reference/orm.html#relational-fields

If you want to use 'parent_id' anyway, then it is better to make a computed m2m field, which would use it but would not redefine it:

@api.multi
@api.depends("parent_id")
def _compute_m2m_parents_ids(self):
    for partner in self:
        if partner.parent_id:
            partner.m2m_parents_ids = [(6, 0, [partner.parent_id.id])]
        else:
            partner.m2m_parents_ids = [(6, 0, [])]            
m2m_parents_ids = fields.Many2many(   
"res.partner",   
"rel_table",    
"back_rel_id",    
"direct_rel_id",      
string="Companies",
    compute=_compute_m2m_parents_ids,
    store=True,
)
Avatar
Discard
Author

thank you

Related Posts Replies Views Activity
0
Apr 18
2340
0
Jul 23
997
1
Jun 23
2131
8
Apr 23
15827
1
Jun 22
3447