When to use api.one and api.multi in odoo | openerp?

前端 未结 3 380
忘掉有多难
忘掉有多难 2021-02-02 01:07

Recently odoo (formerly OpenERP) V8 has been released. In new API method decorators are introduced. in models.py methods needs to be decorated with @api.one

3条回答
  •  遥遥无期
    2021-02-02 01:20

    Generally both decoarators are used to decorate a record-style method where 'self' contains recordset(s). Let me explain in brief when to use @api.one and @api.multi:

    1. @api.one:

    • Decorate a record-style method where 'self' is expected to be a singleton instance.

    • The decorated method automatically loops on records (i.e, for each record in recordset it calls the method), and makes a list with the results.

    • In case the method is decorated with @returns, it concatenates the resulting instances. Such a method:

      @api.one def method(self, args): return self.name

    may be called in both record and traditional styles, like::

    # recs = model.browse(cr, uid, ids, context)
    names = recs.method(args)
    
    names = model.method(cr, uid, ids, args, context=context)
    
    • Each time 'self' is redefined as current record.

    2. @api.multi:

    • Decorate a record-style method where 'self' is a recordset. The method typically defines an operation on records. Such a method:

      @api.multi def method(self, args):

    may be called in both record and traditional styles, like::

    # recs = model.browse(cr, uid, ids, context)
    recs.method(args)
    
    model.method(cr, uid, ids, args, context=context)
    

    When to use:

    1. If you are using @api.one, the returned value is in a list. This is not always supported by the web client, e.g. on button action methods. In that case, you should use @api.multi to decorate your method, and probably call self.ensure_one() in the method definition.

    2. It is always better use @api.multi with self.ensure_one() instead of @api.one to avoid the side effect in return values.

提交回复
热议问题