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

Odoo15中Float类型字段赋值给Char类型字段报错解决方法

问题产生原因

触发该报错的核心原因有3个:

  • 错误给Float数值类型字段添加了translate=True参数:translate翻译属性仅支持Char/Text/Html这类文本类型字段,给Float字段开启翻译后,Odoo ORM会自动生成带COALESCE函数的联表查询,优先取翻译表中存储的text类型值,和原表存储的double precision浮点类型值做合并时,两种数据类型无法匹配,直接触发你看到的PostgreSQL报错。
  • 计算方法缩进错误:_compute_fields_combination方法定义时没有和类内的装饰器、字段保持同级缩进,方法实际被定义到了模型类外部,Odoo无法正确识别该计算方法的作用域。
  • 计算字段依赖不全:@api.depends装饰器只声明了extra_weight、extra_charge两个依赖字段,但拼接逻辑中用到了max_weight字段,字段值变动时不会触发计算字段更新,也会干扰ORM的正常查询逻辑。
正确实现代码
from odoo import fields, models, api

class ExtraWeight(models.Model):
    _name = 'courier.extra.weights'
    _description = 'Charge setting for Extra Weight'
    _rec_name = 'combination'

    # 移除数值字段上不支持的translate参数,修正原字段名的拼写错误(Wight→Weight)
    extra_weight = fields.Float(string='Next (KG)', required=True)
    extra_charge = fields.Float(string='Charge for next Weight (TK)', required=True)
    max_weight = fields.Float(string='Max Weight (KG)', required=True)
    combination = fields.Char('Combination', compute='_compute_fields_combination')

    # 修正方法缩进,补全所有计算逻辑用到的依赖字段
    @api.depends('extra_weight', 'extra_charge', 'max_weight')
    def _compute_fields_combination(self):
        for record in self:
            # 用f-string统一做字符串类型转换,避免ORM类型识别异常
            record.combination = f"Extra Increment:{record.extra_weight}(KG)  Rate{record.extra_charge}(TK) Max:{record.max_weight}(KG)"
优化建议
  • 如果需要控制浮点数的显示精度,避免浮点数精度问题导致显示长尾数(比如2.0显示为2.0000000001),可以在字符串格式化时指定小数位数,例如保留2位小数的写法:
record.combination = f"Extra Increment:{record.extra_weight:.2f}(KG)  Rate{record.extra_charge:.2f}(TK) Max:{record.max_weight:.2f}(KG)"
  • 代码修正后需要重启Odoo服务,通过-u 你的模块名参数升级对应模块,清除旧的字段配置缓存即可正常运行。

内容的提问来源于stack exchange,提问作者Abdus Sattar Bhuiyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:09:46