Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

You can create one record with one2many relation like:

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

You can easily save record in this class

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},.....
               ]
     })

here you can easily pass list of second class object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top