0
votes

I have a one2many which stores some data.

In python, when I need to update the object with .write method; the new data is stored but the old stuff remain there.

How can I empty the many2many before using .write method ??

Maybe using .browse and .search ?? please help !!!

2

2 Answers

2
votes

It would be great if you have posted some example of what you are trying to do. Any way, you have 2 solutions:

  1. use unlink()
  2. understand how the write() ORM method works on one2many fields.

Let take the example of account.invoice and account.invoice.line.

The first approach - unlink():

def delete_lines(self, cr, uid, ids, context=None):
    invoice_pool = self.pool.get('account.invoice')
    line_pool = self.pool.get('account.invoice.line')
    for invoice in invoice_pool.browse(cr, uid, ids, context=context):
        line_ids = [line.id for line in invoice.invoice_line]
        line_pool.unlink(cr, uid, line_ids, context=context)

The second approach - write()

Looking at the OpenERP docs (https://doc.openerp.com/6.0/developer/2_5_Objects_Fields_Methods/methods/#osv.osv.osv.write):

write(cr, user, ids, vals, context=None)
...
Note: The type of field values to pass in vals for relationship fields is specific:

For a one2many field, a lits of tuples is expected. Here is the list of tuple that are accepted, with the corresponding semantics
(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)

So for the vals parameter we need a list of tuples in the following format:

[
    (2, line1_id),
    (2, line2_id),
    (2, line3_id),
    ...
]

The following code illustrates the use of the write() method.

def delete_lines(self, cr, uid, ids, context=None):
    invoice_pool = self.pool.get('account.invoice')
    for invoice in invoice_pool.browse(cr, uid, ids, context=context):
        vals = [(2, line.id) for line in invoice.invoice_line]
        invoice.write(vals)

I didn't test the examples so let me know if they do the job.

0
votes

Here is how I solved it:

my_object = self.pool.get('my.main.object')
props = self.pool.get('table.related')
prop_id = props.search(cr, uid, [('id_1', '=', id_2)])
del_a = []
for p_id in prop_id:
   del_a.append([2, p_id])
my_object.write(cr, uid, line_id, {'many2one_field': del_a}, context=context)

Where: del_a.append([2, p_id]) creates the string of tuples with code "2" (delete) and my_object is where I need to make the changes.