亲宝软件园·资讯

展开

odoo api装饰器 one、model和multi区别

北方男孩 人气:2

## @api.one

新api定义:

1 qty = fields.Integer(string="qty", compute="_get_qty")
2 
3     @api.one
4     def _get_qty(self):
5         self.qty = random.ranint(1, 10)

one一般使用再无返回值,就算添加return也不会返回,也不会报错,版本10以后逐渐淡化

## model

新api定义

@api.model
    def create(self, vals):
        bom_obj = self.search([("product_tmpl_id", '=', vals.get('product_tmpl_id', None))])
        if bom_obj:
            raise UserError('该产品已存在相应的物料清单')
        return super(MrpBom, self).create(vals)

注意:这个方法的注释是这样的:修饰记录样式的方法,其中``self``是记录集,但和内容无关紧要,只有模型相关

假如上面使用mutil装饰就会出错,提示参数个数的报错, 此方法可以有返回值

def model(method):
    """ Decorate a record-style method where ``self`` is a recordset, but its
        contents is not relevant, only the model is. Such a method::

            @api.model
            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, args, context=context)

        Notice that no ``ids`` are passed to the method in the traditional style.
    """
    method._api = 'model'
    return method

## mutil

新api定义

@api.multi
    def search_recursively_line_product(self):
        product_ids = set()
        for rec in self:
            for bom_line in rec.bom_line_ids:
                product_ids.add(bom_line.product_id.id)
                product_tmpl_id = self.env['product.product'].browse(bom_line.product_id.id).product_tmpl_id.id
                bom_line_bom = self.search([('product_tmpl_id', '=', product_tmpl_id)])
                if bom_line_bom.bom_line_ids:
                    product_ids |= bom_line_bom.search_recursively_line_product()
        return product_ids

注:mutil和one时对应的,可以返回一个或者回个记录集

修饰一个记录样式的方法,其中``self``是一个记录集,通常定义对记录的操作

def multi(method):
    """ 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)
    """
    method._api = 'multi'
    return method

 

加载全部内容

相关教程
猜你喜欢
用户评论