Amor.o
Amor.o

Reputation: 540

deal with many2many field in odoo

I have two models skills and res_users.

I want that each user can have many skills and also each skill can have many users on it. I tried to do that but without success.

This is my skills:

class technicians_skills(osv.osv):
_name = 'skills'
_description = 'Technicians Skills'

_columns = {
    'name': fields.char(string='name', size=50),
    'description': fields.text(string="description"),
    'member_ids': fields.many2many('res.users', 'skill', string='Technicians')
} 

and this is the users :

class res_users(osv.osv):
_inherit = 'res.users'

_columns = {
   'skill': fields.many2many('skills', relation='skills.rel', column1='name', column2='skill', string='Skill'),
}

and I want to know the skills of each user, but when I call this :

test = http.request.env['skills.rel'].search([])

It shows me this error

KeyError: 'skills.rel'

Upvotes: 1

Views: 2299

Answers (1)

Charif DZ
Charif DZ

Reputation: 14721

You need to specify all key words in your declaration to create the same relation tables

   fields.many2many(
      comodel_name='model.name',
      relation='valid_postgres_name',
      colum1='current_model_m2o_field_name',
      column2='comodel_m2o_name',
      string='Label')

And in the other definition keep the same name of the relation but inverse the other keyword.

In skills

  user_ids = fields.many2many('re.users', 'user_skill_rel','user_id','skill_id', 'Users')

In users

skill_ids = fields.many2many('skills',  'user_skill_rel', 'skill_id', 'user_id', 'Skills')

See how i inversed the definition only the relation is the same. Keep the same names of columns

EDITS:

don't execute search on relation because they are not models. you need to execute the search on the model then access the many2many fields.

Let say you want to get skill of the current user.

   self.env.user.skill_ids  # this will return the list of the skills for the current user

if you want to get the skills of more than one user.

  result = self.env['res.users'].search([your_domain]])

  # if you need to show user information then it's skill
  for rec in result:
       # use loop
       rec.name # user name
       rec.skill_ids

  # but if you want to get the list of skill and you don't need users
  skills = result.mapped('skills_ids')  # mapped will return all the skills without duplication

Upvotes: 1

Related Questions