How to create record adding one2many values?

Andrius picture Andrius · Apr 1, 2014 · Viewed 14.5k times · Source

Let say I have such classes:

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'),
    }

Now I want to write a method, when it is called, it would create First class record taking values from Second class. But I don't understand how I should pass values in one2many field while creating First class.

For example let say I call create like this (this method is inside Second class):

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

There is a documentation about inserting one2many values here: https://doc.openerp.com/v6.0/developer/2_5_Objects_Fields_Methods/methods.html/#osv.osv.osv.write

But that is only for write method.

Answer

Bhavesh Odedra picture Bhavesh Odedra · Apr 2, 2014

Try this Values, If the second.class obj has partner than one2many is created.

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)