Odoo14 rpc
阅读原文时间:2023年07月08日阅读:3

odoo14中rpc调用分为两种。

一种是外部调用rpc来访问odoo数据,这个时候你需要登录授权。

另一种是我们自己编写的widget小部件或者自定义视图时候通过js通过rpc去获取数据。

这里说的是第二种rpc的使用。

上代码:

//调用res.users中的自定义的get\_userform\_action方法  
this.\_rpc({  
    model: 'res.users',  
    method: 'get\_userform\_action',  
    args: \[\[data.val\]\]//这里就是python函数声明里的\*args,当你的方法不是model方法也不是model\_create方法的时候,这里一个参数传的是当前model(res.users)的记录id,它会查询id结果作为self去调用get\_userform\_action  
}).then(function (result){  
    self.do\_action(result);  
});

//查询数据的方法  
this.\_rpc({  
    model: this.model,  
    method: 'read\_group',  
    domain: \[\],  
    fields: \['color'\],  
    groupBy: \['color'\],  
}).then(function (result) {  
    \_.each(result, function (r) {  
        self.colorGroupData\[r.color\] = r.color\_count;  
    });  
});

//自定义的方法
class Users(models.AbstractModel):
_inherit = 'res.users'

def get\_userform\_action(self):  
    action = self.env.ref('ship\_manage.res\_company\_user\_form\_action').read()\[0\]  
    action\['res\_id'\] = self.id  
    return action

1 //Python rpc参数传递源码
2 def _call_kw_model(method, self, args, kwargs):
3 context, args, kwargs = split_context(method, args, kwargs)
4 recs = self.with_context(context or {})
5 _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
6 result = method(recs, *args, **kwargs)
7 return downgrade(method, result, recs, args, kwargs)
8
9
10 def _call_kw_model_create(method, self, args, kwargs):
11 # special case for method 'create'
12 context, args, kwargs = split_context(method, args, kwargs)
13 recs = self.with_context(context or {})
14 _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
15 result = method(recs, *args, **kwargs)
16 return result.id if isinstance(args[0], Mapping) else result.ids
17
18
19 def _call_kw_multi(method, self, args, kwargs):
20 ids, args = args[0], args[1:]
21 context, args, kwargs = split_context(method, args, kwargs)
22 recs = self.with_context(context or {}).browse(ids)
23 _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
24 result = method(recs, *args, **kwargs)
25 return downgrade(method, result, recs, args, kwargs)
26
27
28 def call_kw(model, name, args, kwargs):
29 """ Invoke the given method ``name`` on the recordset ``model``. """
30 method = getattr(type(model), name)
31 api = getattr(method, '_api', None)
32 if api == 'model'://这里将模型分成了三种走向,三种走向对参数的处理不一样
33 result = _call_kw_model(method, model, args, kwargs)
34 elif api == 'model_create':
35 result = _call_kw_model_create(method, model, args, kwargs)
36 else:
37 result = _call_kw_multi(method, model, args, kwargs)
38 model.flush()
39 return result