Search code examples
pythonodookeyerror

How to fix KeyError in python --> KeyError: 'compensation_remaining_leaves'


i have problem with my code, the problem is KeyError, I spent hours but did not find the mistake, KeyError: days_compensation_remaining

Here's my code.

Class and Model:

class HrEmployee(models.Model):
    _inherit = 'hr.employee'

    days_compensation_remaining = fields.Float(
        'Jours de récupération restant',
        compute='_compute_days_compensation_remaining',
        readonly=True,
        inverse='_inverse_days_compensation_remaining',
        help='Nombre total des jours de récupération '
        )

My first function:

    @api.multi
    def _inverse_days_compensation_remaining(self):
        self.ensure_one()
        days_compensation = self.company_id.days_compensation_holidays_status_id
        if not compensation_legal_leave:
            raise UserError(_("le type de congé pour les jours de récupération n'est pas défini"))
        diff = self.days_compensation_remaining - compensation_legal_leave.get_days(
            self.id)[compensation_legal_leave.id]['days_compensation_remaining']

If the difference is greater than 0:

if diff > 0:
                leave = self.env['hr.holidays'].create(
                    {
                        'name': 'Allocation for %s' % self.name,
                        'employee_id': self.id,
                        'holiday_status_id': compensation_legal_leave.id,
                        'type': 'add',
                        'holiday_type': 'employee',
                        'number_of_days_temp': diff
                    }
                )
                leave.action_approve()
                if leave.double_validation:
                    leave.action_validate()
            elif diff < 0:
                raise UserError(_('vous ne pouvez pas réduire le nombre de jours'))

My second function:

    @api.multi
    def _compute_days_compensation_remaining(self):
        for r in self:
            compensation_legal_leave = r.company_id.days_compensation_holidays_status_id
            if not compensation_legal_leave:
                raise UserError(_("le type de congé pour les jours de récupération n'est pas défini"))
            r.days_compensation_remaining = compensation_legal_leave.get_days(
                r.id)[compensation_legal_leave.id]['days_compensation_remaining'] 

Solution

  • There is nothing wrong in your code, but it is due to the input which you received. A lot of times we don't get the desired values, hence we should write the code such that when a key is not present still our code doesn't break and work as desired.

    You should use the input_obj.get('key', default_value) syntax which will help you get through even when the key is not present and if not present then you can give default value. There are other ways to do it such as hasattr which is explain very well here.