Hello, I am currently working on a module that has a model with a start and end date. I'm trying to work out how to create one2many records for each day from start to end, automatically during the creation of a record. See the code:
class Order(models.Model):
_name = 'tms.order'
company_id = fields.Many2one('res.company',string = 'Client')
description = fields.Text()
start_date = fields.Datetime('Start Date',required = True)
end_date = fields.Datetime('End Date',required = True)
start_location = fields.Char()
end_location = fields.Char()
driver = fields.Many2one('hr.employee',string = 'Driver',required = True)
vehicle = fields.Many2one('fleet.vehicle')
working_days = fields.One2many('tms.day','order', ondelete='cascade')
@api.model
def create(self, vals):
print(vals)
start = parser.parse(vals['start_date'])
stop = parser.parse(vals['end_date'])
if start < stop:
while start < (stop + timedelta(days=1)):
vals['working_days'] = self.env['tms.day'].create((0,0,{'date':start, 'driver': vals['driver']}))
start = start + timedelta(days=1) # increase day one by one
return super(Order, self).create(vals)class Day(models.Model):
_name= 'tms.day'
date = fields.Date()
utilisation_ratio = fields.Float("Utilisation ratio", compute='calculate_utilisation_ratio')
driver = fields.Many2one('hr.employee',string = 'Driver')
order = fields.Many2one('tms.order')
@api.depends('date')
def calculate_utilisation_ratio(self):
total_number_of_drivers = self.count_total_drivers()
for day in self:
drivers_working_today = self.env['tms.day'].search_count([('date','=',day.date)])
day.utilisation_ratio = drivers_working_today/total_number_of_drivers
def count_total_drivers(self):
return self.env['hr.employee'].search_count([])
The above code produces tms.day records automatically with the creation of an tms.order, but the tms.days are not linked to any tms.orders. How can I link the Orders to the Days?