2014-04-08 60 views
0

我有一个one2many它存储一些数据。OpenERP - many2one删除旧数据

python,当我需要更新对象.write方法;新的数据被存储,但旧的东西仍然存在。

如何在使用之前清空many2many .write方法??

也许使用.browse.search ??请帮忙 !!!

回答

2

如果您发布了一些您正在尝试做的事情,那将会很棒。无论如何,你有2个解决方案:

  1. 使用unlink()
  2. 了解write() ORM方法是如何工作的one2many领域。

我们以account.invoiceaccount.invoice.line为例。

第一种方法 - 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) 

第二种方法 - write()

望着OpenERP的文档(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) 

所以对于vals paramete [R,我们需要一个元组列表中的格式如下:

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

下面的代码说明了write()方法。

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) 

我没有测试这些例子,所以让我知道他们是否做这项工作。

+0

谢谢你的答案;我发布了我是如何解决它的,这几乎是你的第二选择。 –

0

这是我如何解决它:

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) 

其中: del_a.append([2的p_id])创建了代码的元组字符串 “2”(删除) 和my_object是我需要进行更改的地方。