Automatically incrementing number in target model

There is a list of employees in our application.
Each employee has a list of records with a unique number within this list.
When adding a new record for an employee, the number is automatically incremented.

class Empl(ModelSQL, ModelView):
    __name__ = 'module.empl'
    list = fields.One2Many('module.list', 'empl_id', 'List')

class List(ModelSQL, ModelView):
    __name__ = 'module.list'
    empl_id = fields.Many2One('module.empl', 'Empl_id')
    number = fields.Numeric('Number')

    def default_number(cls):
        employee_id = ?????
        lines =
            [('empl_id', '=', employee_id),
            ], order=[('number', 'DESC')], limit=1)
        if lines:
            number = lines[0].number + 1
            number = 1
        return number

Is it possible to get id of the current employee (employee_id) in the method default_number?

No you can not have it. Default methods are called before any field are filled.
But you can update the number field using an on_change on the empl_id (strange to suffix with id).
Also be careful that your code does not work on concurrent environment and neither if you add more than 1 line at a time.
If you just want to have an order, you should use the sequence_ordered mixin and activate the sequence on the tree view.
If you want to have sequential numbering, you may use an ir.sequence and fill the field on create like the sale. But in your case you will need to create a sequence for each employee.

It seems too expensive to create a sequence for each employee.
So we will update the number field using the method on_change.
In addition, our users can edit the number in the employee list.
In concurrent environment they may receive an error message about the number uniqueness.

Thanks Cedric for the help and detailed answer.

We have found a better solution to our problem.
We used on_change_list method of Empl class instead of on_change_empl_id method of List class:

def on_change_list(self):
    if self.list[-1].number == 0:
        max_number = max([x.number for x in self.list])
        self.list[-1].number = max_number + 1

And there is default_number method in List class:

def default_number():
    return 0

Of course this solution does not work on concurrent environment, but it works if we add more than 1 line at a time.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.