如何创建添加one2many值的记录?

时间:2014-04-01 13:23:15

标签: python openerp openerp-7

我想说我有这样的课程:

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类中获取值。但是我不明白在创建one2many课程时我应该如何在First字段中传递值。

例如,假设我调用create这样(此方法在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值的文档: https://doc.openerp.com/v6.0/developer/2_5_Objects_Fields_Methods/methods.html/#osv.osv.osv.write

但这只适用于写方法。

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:3)

您可以使用one2many关系创建一条记录,例如:

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

答案 2 :(得分: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},.....
               ]
     })

这里你可以轻松传递第二类对象列表