This question has been flagged
1 Reply
5663 Views

I am using Odoo Studio online.  I have a server side action I'm trying to write to copy tags from a many2many field in the parent to all the children.  To test I used a char field to ensure I can write from the parent to the child and it works.  The code looks like this.

record.child_ids.write({'ref': 'Test'})

I confirmed that all of the child records have the word "Test" in the "ref" field.

Now I want to do the same with a many2many field.  I'm having trouble understanding what to do here.  I did find that with many2many fields you have to change things up a bit.

(0, 0, { values }) link to a new record that needs to be created with the given values dictionary

(1, ID, { values }) update the linked record with id = ID (write values on it)

(2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)

(3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)

(4, ID) link to existing record with id = ID (adds a relationship)

(5) unlink all (like using (3,ID) for all linked records)

(6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)

I was thinking i need to use (1, ID, { values }) .

I tried this.

#record.child_ids.write({'x_tags': [1,record.id,'TEST']})

  1. I'm not entirely sure if I'm supposed to put the id of the current record in the ID spot (record.id)

  2. My tags field does pull from a related table. So I'm guessing that I can't just fill in "TEST" since it's not part of the records already in the related table.  Do I need to put the path to the related table there? I'm not sure what it is looking for.

  3. For me to copy the data from the parent field to the child field do I have to somehow create a dictionary of the current entries in that field and then write those to the children?

Hopefully someone has done this and can help me out a bit here.  Thanks in advance.

Avatar
Discard
Author Best Answer

So I managed to solve it.  Hopefully this will help someone else.  I'm not sure if it is the best way to do it but this seems to work.

tagids = []

tagids = record.x_tags.ids

record.child_ids.write({'x_tags': [(6,0,tagids)]})

And if you are in the child record and you want to copy the values from the parent, you can do the following.  (This is helpful if you were to perhaps create a new child record and you wanted to get the values from the parent on_creation)

tagsids = []

tagids = record.parent_id.tag_id.ids

record.write({'tag_id': [(6,0,tagids)]})

manuf_tagids = []

Avatar
Discard

This was very helpful and worked for some field syncing across models