【发布时间】:2014-04-08 20:42:13
【问题描述】:
我有一个存储一些数据的 one2many。
在python中,当我需要用.write方法更新对象时;新数据被存储,但旧数据仍然存在。
如何在使用 .write 方法之前清空 many2many ??
也许使用 .browse 和 .search ??请帮忙!!!
【问题讨论】:
我有一个存储一些数据的 one2many。
在python中,当我需要用.write方法更新对象时;新数据被存储,但旧数据仍然存在。
如何在使用 .write 方法之前清空 many2many ??
也许使用 .browse 和 .search ??请帮忙!!!
【问题讨论】:
如果您发布了一些您正在尝试做的事情的示例,那就太好了。无论如何,您有 2 个解决方案:
unlink()
write() ORM 方法如何作用于one2many 字段。 以account.invoice和account.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)
我没有测试这些示例,所以请告诉我他们是否可以完成这项工作。
【讨论】:
我是这样解决的:
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 是我需要进行更改的地方。
【讨论】: