如何添加一对多关系的记录?
假设我有这样的类:
class First(orm.Model):
_name = 'first.class'
_columns = {
'partner_id': fields.many2one('res.partner', 'Partner'),
'res_ids': fields.one2many('second.class', 'first_id', 'Resources'),
}
class Second(orm.Model):
_name = 'second.class'
_columns = {
'partner_id': fields.many2one('res.partner', 'Partner'),
'first_id': fields.many2one('first.class', 'First'),
}
现在我想写一个方法,当这个方法被调用时,它会创建一个First
类的记录,并从Second
类中获取值。但是我不太明白在创建First
类时,应该如何传递one2many
字段的值。
举个例子,假设我这样调用创建方法(这个方法在Second
类里面):
def some_method(cr, uid, ids, context=None):
vals = {}
for obj in self.browse(cr, uid, ids):
#many2one value is easy. I just link one with another like this
vals['partner_id'] = obj.partner_id and obj.partner_id.id or False
#Now the question how to insert values for `res_ids`?
#`res_ids` should take `id` from `second.class`, but how?..
vals['res_ids'] = ??
self.pool.get('first.class').create(cr, uid, vals)
return True
这里有关于插入one2many
值的文档:
但是那只是针对写入方法的说明。
3 个回答
1
你可以很简单地在这个类里保存记录。
first_class_obj.create(cr,uid,{
'partner_id':partner.id,
res_ids : [
{'partner_id':parner_1.id},
{'partner_id':parner_2.id},
{'partner_id':parner_3.id},.....
]
})
在这里,你可以轻松地传递第二个类的对象列表。
4
你可以通过一对多的关系来创建一个记录,像这样:
invoice_line_1 = {
'name': 'line description 1',
'price_unit': 100,
'quantity': 1,
}
invoice_line_2 = {
'name': 'line description 2',
'price_unit': 200,
'quantity': 1,
}
invoice = {
'type': 'out_invoice',
'comment': 'Invoice for example',
'state': 'draft',
'partner_id': 1,
'account_id': 19,
'invoice_line': [
(0, 0, invoice_line_1),
(0, 0, invoice_line_2)
]
}
invoice_id = self.pool.get('account.invoice').create(
cr, uid, invoice, context=context)
return invoice_id
5
试试这些值,如果 second.class obj
有 partner
,那么就会创建一个 one2many
的关系。
obj = self.browse(cr, uid, ids)[0]
if obj.partner_id:
vals{
'partner_id': obj.partner_id.id,
'res_ids': [(0,0, {
'partner_id': obj.partner_id.id, #give id of partner
'first_id': obj.first_id.id #give id of first
})]
}
self.pool.get('first.class').create(cr, uid, vals)