I have two models. One model has an One2Many field pointing to the other one. When I save the main record, it only saves one record of the One2many relation. I need it to save 'n' records. Maybe the problem is the structure of the data I planned.
Here is the code. I'm sorry for the Spanish names of the variables.
Thanks in advance.
This is the first class it calls the second class with One2Many relation.
class EmpleadosProductos(models.Model): _name = "employee.as.product"
#the One2Many relation of the trouble
employee_line = fields.One2many(
'employee.line',
'id',
string='Employee Lines',
store=True
)
companyias = fields.Many2one('res.partner', 'Compañia', domain=[('is_company', '=', True)])
amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_calcularTotal')
journal_entry = fields.Many2one('account.move')
currency_id = fields.Many2one('res.currency', 'Currency', required=True, default=lambda self: self.env.user.company_id.currency_id.id)
fecha = fields.Date('Fecha')
referencia = fields.Char(string='Ref', required=True)
_sql_constraints = [
('refererecia_constraint', 'unique(referencia)', 'La referencia debe de ser única!'),
]
@api.one
@api.depends('employee_line.total')
def _calcularTotal(self):
for empleado_obra in self:
acumulador = 0.0
for linea in empleado_obra.employee_line:
acumulador += linea.total
empleado_obra.update({
'amount_total': acumulador
})
This is the second class called in the One2Many relation.
class EmployeLine(models.Model):
_name = 'employee.line'
descripcion = fields.Text(string='Descripción', required=False)
employee_id = fields.Many2one(
'hr.employee',
string="Empleado",
requiered=True,
change_default=True
)
currency_id = fields.Many2one('res.currency', 'Currency', required=True, default=lambda self: self.env.user.company_id.currency_id.id)
apodo = fields.Char('apodo', readonly=False)
precio_por_hora = fields.Float('Sueldo/hora', store=True)
numero_de_horas = fields.Integer('Número de horas', store=True)
total = fields.Monetary(string='Total', store=True, readonly=True, compute='_calcularTotalLine')
_rec_name = 'apodo'
@api.one
@api.depends('numero_de_horas', 'precio_por_hora')
def _calcularTotalLine(self):
self.update({
'total': (self.precio_por_hora * self.numero_de_horas)
})
@api.onchange('employee_id')
def onchange_employee_id(self):
addr = {}
if not self.employee_id.display_name:
return addr
if not self.employee_id.apodo:
self.apodo = "no apodo"
else:
self.apodo = self.employee_id.apodo
self.precio_por_hora = self.employee_id.precio_por_hora
return addr