首页 > 解决方案 > Odoo 开发中何时、为什么以及如何避免 KeyError

问题描述

我注意到我开发的一些自定义模块可以安装在有记录的数据库上,而另一些则抛出 KeyError 消息,除非数据库为空(无记录)。通常,当模块包含计算字段时会出现错误。那么,有人知道为什么会这样吗?以及我的代码应该如何避免这种错误?抛出此错误的示例计算字段如下所示:

from odoo import models, fields, api
from num2words import num2words

Class InheritingAccountMove(models.Model):
   _inherit = 'account.move'

total_amount_text = fields.Char(string='Total', compute='_compute_total_amount_text', store=True)

    @api.depends('amount_total')
    def _compute_total_amount_text(self):
        lang_code = self.env.context.get('lang') or self.env.user.lang
        language = self.env['res.lang'].search([('iso_code', '=', lang_code)])
        separator = language.read()[0]['decimal_point']
        for record in self:
            decimal_separator = separator
            user_language = lang_code[:2]
            amount = record.amount_total
            amount_list = str(amount).split(decimal_separator)
            amount_first_part = num2words(int(amount_list[0]), lang=user_language).title() + ' '
            amount_second_part = amount_list[1]
            if len(amount_second_part) == 0:
                amount_text = amount_first_part + '00/100'
            elif len(amount_second_part) < 2:
                amount_text = amount_first_part + amount_second_part + '0/100'
            else:
                amount_text = amount_first_part + amount_second_part[:2] + '/100'

            record.total_amount_text = amount_text

标签: keyerrorodoo-13computed-field

解决方案


更新
您的代码在这种情况下出现问题的原因是,当表中没有记录时(在安装时),您的循环将不会运行,这导致您的计算字段没有赋值,因此添加第一行代码在函数中
self.total_amount_text = False
这是从 Odoo 13 和可能 12 为计算函数中的计算字段分配值所必需的
----------------------------- -----------------------------------
其他原因可能是:
尝试访问密钥时会发生此错误来自不存在的字典,例如,

language.read()[0]['decimal_point']

在安装模块时,字典可能没有“decimal_point”,这可能会返回此错误,处理此错误的常用方法是在访问它之前检查密钥是否存在,

if 'decimal_point' in language.read()[0].keys() 此外,字典也可以是在这种情况下为空language.read()[0]将引发错误


推荐阅读