如何通过Odoo JsonRPC默认API单次read调用获取嵌套字段内容?
Odoo JSON-RPC默认API读取嵌套字段的实现方法
Odoo默认JSON-RPC的read方法不支持像customer_id__email这种双下划线的嵌套字段写法——这种格式会被识别为当前模型不存在的字段,直接返回错误。
要获取Many2One、One2Many或Many2Many这类关联字段的嵌套内容,得按以下方式处理:
1. 处理Many2One字段(如customer_id)
read方法只会返回Many2One字段的记录ID和显示名称(格式为[ID, 显示名]),要获取关联模型的具体字段,需要分两步:
- 第一步:调用当前模型的
read方法,获取关联字段的ID - 第二步:调用关联模型的
read方法,传入ID并指定需要的字段
示例请求:
获取合同关联的客户ID
{ "jsonrpc": "2.0", "params": { "model": "car.rental.contract", "method": "read", "args": [[7]], "kwargs": { "fields": ["customer_id"] } } }
返回结果中customer_id会是类似[123, "John Doe"]的格式,接着用这个ID请求客户邮箱:
获取客户邮箱
{ "jsonrpc": "2.0", "params": { "model": "res.partner", "method": "read", "args": [[123]], "kwargs": { "fields": ["email"] } } }
2. 处理One2Many/Many2Many字段
read方法返回这类字段的记录ID列表,要获取这些记录的具体内容,同样需要单独调用对应模型的read方法,传入ID列表和目标字段。
比如合同的rental_lines(One2Many字段),先获取ID列表:
{ "jsonrpc": "2.0", "params": { "model": "car.rental.contract", "method": "read", "args": [[7]], "kwargs": { "fields": ["rental_lines"] } } }
返回rental_lines为[456, 457],再调用对应模型读取详情:
{ "jsonrpc": "2.0", "params": { "model": "car.rental.line", "method": "read", "args": [[456, 457]], "kwargs": { "fields": ["car_id", "start_date"] } } }
3. 单次请求获取嵌套字段的方案
如果想在单次请求里完成,可以在目标模型中自定义一个ORM方法,封装嵌套字段的查询逻辑,再通过JSON-RPC调用这个自定义方法。
比如在car.rental.contract模型中添加Python方法:
def get_contract_with_customer_email(self): self.ensure_one() return { "id": self.id, "contract_name": self.name, "customer_email": self.customer_id.email if self.customer_id else False }
然后通过JSON-RPC调用这个方法:
{ "jsonrpc": "2.0", "params": { "model": "car.rental.contract", "method": "get_contract_with_customer_email", "args": [[7]] } }
内容的提问来源于stack exchange,提问作者Arlème Johnson
相关产品推荐
相关产品推荐

