Search code examples
keyerrorodoo-13computed-field

When, why and how to avoid KeyError in Odoo Development


I´ve noticed that some custom modules that I develop can be installed on databases with records, while others throw the KeyError message, unless the database is empty (no records). Generally the errors appear when the module contains computed fields. So, does anybody know why this happens? and how my code should look like to avoid this kind of errors? an example computed field that throws this errors looks like this:

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

Solution

  • UPDATED
    The reason your code has a problem in this situation is that when there are no records in the table(at time of installation) your loop won’t run which result in no value assigning of your computed field so Add the first line of code in function
    self.total_amount_text = False
    This is required to assign value to the computed field in compute function from Odoo 13 and maybe 12
    ----------------------------------------------------------------
    Other reasons could be :
    This error occurs when one tries to access a key from a dictionary that doesn't exist like,

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

    the dictionary may not have 'decimal_point' at the time of installation of the module, which may have returned this error a common way to handle this is by checking if the key exists or not before accessing it like,

    if 'decimal_point' in language.read()[0].keys() also, a dictionary can also be empty in that case the language.read()[0] will throw an error