Skip to Content
Menu
This question has been flagged
1 Reply
19267 Views

In v8 I have three models, ModelA, ModelB and ModelC.

  • ModelA has a One2many field: field_b_ids relating ModelA and ModelB.
  • ModelB has a Many2many field: field_c_ids relating ModelB and ModelC.

​Somewhere else I have one id for one ModelA record (a_id).
Doing:

my_a = self.env['model.a'].search([('id', '=', a_id)])

I get the recordset with the one ModelA record I expect. 
From there, I need to get all the ids (or records in a recordset) of ModelC that are in field_c_ids in those ModelB records which are in field_b_ids in my ModelA record.

I thought using mapped() (as read in http://odoo-new-api-guide-line.readthedocs.org/en/latest/environment.html#useful-helpers ) would be my solution, like this:

my_c_ids = my_a.mapped(field_b_ids.field_c_ids)

But mapped() seems to work OK with everything except One2many and Many2many.

Also, trying to go step by step, using loops, if I try to get the ModelB records like this:

my_b_ids = my_a.field_b_ids

This fails complaining about expecting singleton, even if I do:

for a in my_a:

    my_b_ids = a.field_b_ids

I tried variations on this, like using a.field_b_ids[0][2] (seen for XML domains in https://www.odoo.com/forum/help-1/question/how-to-define-a-domain-for-a-field-a-depending-on-the-ids-of-other-field-b-in-a-view-73115 , but it seems to work only in XML domains, not in Python code).

So... How do I get it?

I am running completely out of options here. I feel like it should be easier for o2m, m2m and be (better) documented.

--------

EDIT: [SOLVED]

I already found the problem: I was defining a field as One2many when it should be Many2many (to work with its Many2many counterpart).
Once fixed that, everything works fine and the use of mapped() feels nice and super-easy.

 

 

Avatar
Discard
Best Answer

my_a is a list of integers (database IDs), you should do self.env['model.a'].browse(my_a) first to get the recordset.  After which you should be able to chain it:

for a in self.env['model.a'].browse(my_a):

    my_b_ids = a.field_b_ids

 

Avatar
Discard
Author

But in v8 new API search() returns also a recordset, not a list of ids anymore. (See https://www.odoo.com/documentation/8.0/reference/orm.html#common-orm-methods )

My apology, you're right. Reading further to the link that you have shared in your question. The example stated that you need to supply a string to mapped. Your code does not seems to supply a string. Maybe that is the problem?

Author

I found my problem already. A simple stupid one: I defined a field as One2many, when it should be Many2many to be correct. With that fix, mapped works like a charm! (I will edit my question to state this)

Related Posts Replies Views Activity
2
Feb 20
17320
1
Sep 15
5062
2
Mar 15
7222
3
Apr 20
10684
1
May 19
9636