Odoo中从one2many字段获取最后更新数据的问题排查
解决Odoo中One2many字段新建记录时Compute字段不生效的问题
看来你在Odoo开发中遇到了个典型小问题:已有记录能正常从weather_ids取最新更新的温度数据,但新建记录时temperature字段就是不生效。我帮你梳理下问题根源和修复方案:
先把你未完成的代码补全并修正,核心问题基本出在compute方法的依赖声明和空值处理上:
from odoo import models, fields, api class Location(models.Model): _name = 'weather.location' _description = 'Weather Location' name = fields.Char(string="City Name", required=True) weather_ids = fields.One2many('weather.weather', 'location_id', string="Weather Details", domain=[('forecast', '=', False)]) # 可选store=True,将计算结果持久化到数据库,提升后续访问性能 temperature = fields.Float(string='Temperature', compute='_compute_weather_details', store=True) @api.depends('weather_ids', 'weather_ids.write_date') def _compute_weather_details(self): for rec in self: # 按更新时间倒序取最新记录;未保存的新记录用create_date兜底排序 last_weather = rec.weather_ids.sorted(lambda w: w.write_date or w.create_date, reverse=True)[:1] # 处理新建记录时weather_ids为空的场景,避免报错 rec.temperature = last_weather.temperature if last_weather else 0.0
下面拆解关键修复点:
添加
@api.depends依赖声明
你之前的代码大概率没加这个装饰器,Odoo需要明确知道哪些字段变化时要触发compute计算。这里我们依赖weather_ids本身和它的write_date,确保新增、删除或修改天气记录时,都会重新计算温度。空值场景处理
新建location记录时,weather_ids必然是空的,如果直接取最后一条会触发隐性错误。我们通过判断给温度设置默认值(你可以根据需求改成空或者其他数值)。兼容未保存记录的排序逻辑
刚创建的weather记录还未保存,write_date为空,这时候用create_date兜底排序,确保能拿到最新创建的那条数据。
如果想让表单里的温度实时更新(不用点击保存就能看到变化),可以额外添加一个onchange方法:
@api.onchange('weather_ids') def _onchange_weather_ids(self): self._compute_weather_details()
这样在界面上添加或删除天气记录时,温度字段会立刻同步更新。
总结你之前的问题根源:
- 未声明compute方法的依赖,导致新建记录或更新one2many字段时,计算逻辑未被触发;
- 未处理one2many字段为空的情况,新建记录时可能抛出隐性错误,导致字段不显示;
- 排序逻辑未考虑未保存记录的时间字段为空的场景。
内容的提问来源于stack exchange,提问作者user_123
相关产品推荐
相关产品推荐

