0

I'm getting an expected singleton error after adding a many2many field in my search_count condition.

The structure consists of 3 classes, job, location, and employee. What I'm trying to do is to get the number of employees of each job at each location.

This works as expected with a many2many widget in xml:

(String parameters were excluded)

class job(models.Model):
  _inherit               = 'hr.job'

  rel_locations          = fields.Many2many(comodel_name='hr.locations')

  num_location_employees = fields.Integer(compute='_set_location_employees')

  def _set_location_employees(self):
     for rec in self:
        rec.num_location_employees = self.env['hr.employee'].search_count([('locations', '=', 3)])

It gives me a list of jobs with the number of employees in location with id 3.

However, after changing the id of 3 to

('locations', '=', rec.rel_locations.id)

I get

Expected singleton: hr.locations(3,4)

Here is the essential locations class

class locations(models.Model):
  _name          = 'hr.locations'

  employee       = fields.One2many(comodel_name='hr.employee', inverse_name='locations')
  rel_jobs       = fields.Many2many(comodel_name='hr.job')

  name           = fields.Char(...)

I'm still pretty new to this and any help would be appreciated. Thanks in advance.

huaa
  • 47
  • 2
  • 6

2 Answers2

1
  1. You should be using ids instead of id
  2. In your domain use in instead of =

Like this:

('locations', 'in', rec.rel_locations.ids)

Let me know if it works.

Rutul Raval
  • 313
  • 2
  • 10
  • I just tried this and it appears I'm still getting the problem. I have a feeling it has something to do with the list of jobs in each location record. The issue only appeared after I added entries to the job list in the second location record. I'm going to try and narrow down the cause some more. Thank you for the taking the time to reply. – huaa Jan 31 '16 at 00:35
0

You can only use the dot notation (.) to access a single record and you have multiple ones there. Check the documentation on the part that says field access

Trying to read or write a field on multiple records will raise an error.

The rec.rel_locations is an ORM one2many that contains 2 records to hr.locations model. You have first get the id of each of those records and then create your domain like this:

('locations', 'in', [rel_location_id1,rel_location_id2])

For more information check the documentation part I have posted and also:

1 2

Community
  • 1
  • 1
George Daramouskas
  • 3,720
  • 3
  • 22
  • 51
  • This was an informative answer and it helped me understand what I was doing wrong. My approach to my problem was completely off. So I ended up scrapping this. Thanks for the detailed response. – huaa Feb 03 '16 at 20:00