OpenERP - many2one删除旧数据

时间:2014-04-08 20:42:14

标签: field openerp

我有 one2many ,可存储一些数据。

python 中,当我需要使用 .write 方法更新对象时;存储了新数据,但旧的东西仍在那里。

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

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

2 个答案:

答案 0 :(得分:2)

如果您发布了一些您想要做的事情的例子,那就太棒了。无论如何,你有2个解决方案:

  1. 使用unlink()
  2. 了解write() ORM方法如何在one2many字段上运行。
  3. 我们以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参数,我们需要以下列格式的元组列表:

    [
        (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)
    

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

答案 1 :(得分: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 是我需要进行更改的地方。