To create a self-related Many2many relation, the following parameters must be used: relation, column1 and column2. The value given to the former parameter will become the table name in the database, while the values given to column1 and column2 will become field names for the afore mentioned table so, in order to add attributes, we simply declare a new model which uses exactly the same table and fields, thus tricking the Odoo's ORM.
from openerp import api, fields, models
class MainModel(models.Model):
_name = 'mymodule.mainmodel'
# See https://www.odoo.com/documentation/10.0/reference/orm.html#relational-fields
related_ids = fields.Many2many('mymodule.mainmodel', relation='mymodule_mainmodel_rel', column1='left', column2='right', string='Related instances')
# ... more field definitions
class MainmodelRelations(models.Model):
_name = 'mymodule.mainmodel.rel'
left = fields.Integer(string='Left', required=True)
right = fields.Integer(string='Right', required=True)
# ... more field definitions:
relationship = fields.Selection(string='Left to Right Relationship', selection='_get_relationship', required=True)
def _get_relationship(self):
return [
('01','relationship1'),
('02','relationship2'),
('03','relationship3')#,
# ... and so on
]
# In case the relationship is not reflexive, otherwise this can be omitted
@api.one
@api.constrains('left', 'right')
def _check_description(self):
if self.left == self.right:
raise ValidationError("A MainModel instance cannot be related to itself.")
Note: This is a redacted code taken from one that worked for me with Odoo 10 but I'm confident it works with earlier versions.