You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo技术问询:如何从Plane模型获取关联匹配的seats_number字段

优化Odoo Flight模型中seats_number计算方法

原代码存在的问题

  • 循环遍历所有airport.plane记录,当飞机数据量大时,会严重拖慢性能
  • 逻辑隐患:如果plane_id是many2one关联字段,直接和plane.name做对比是对象与字符串的无效比较,永远无法匹配;就算plane_id是存储名称的字符字段,全表遍历的方式也完全没必要

正确实现方案

分两种场景给出最优写法:

场景1:plane_id是many2one关联到airport.plane(Odoo标准关联方式)

这是最合理的设计,直接通过关联字段取值即可:

@api.depends('plane_id')
def _compute_seats_number(self):
    for flight in self:
        # 处理plane_id为空的情况,避免报错
        flight.seats_number = flight.plane_id.seats_number if flight.plane_id else 0

场景2:plane_id是存储飞机名称的字符字段(非标准设计,不推荐)

如果业务确实需要用名称匹配,用批量查询+字典映射的方式优化性能:

@api.depends('plane_id')
def _compute_seats_number(self):
    # 先收集所有需要匹配的飞机名称,批量查询一次数据库
    plane_names = self.mapped('plane_id')
    planes = self.env['airport.plane'].search([('name', 'in', plane_names)])
    # 构建名称到座位数的映射,后续直接取值
    plane_seats_map = {plane.name: plane.seats_number for plane in planes}
    
    for flight in self:
        # 用get方法处理名称不存在的情况,默认返回0
        flight.seats_number = plane_seats_map.get(flight.plane_id, 0)

优化核心点

  1. 避免全表遍历,改用批量查询减少数据库交互次数
  2. 用字典映射实现O(1)时间复杂度的匹配,替代循环比对
  3. 处理空值边界情况,防止运行时报错

内容的提问来源于stack exchange,提问作者user21681228

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 15:03:22