I am very new to Django rest framework and stack overflow even, I was struggling with finding a title so please feel free to give a better alternative.
I have a set of jobs that get posted to a database. the jobs are now grouped per machine and per given hour. For now I am only displaying the total count of jobs per hour. My API end point looks like this now : Api end point
Here's where I am struggling: I need to get the duration of the job separated by hour. I have a Datetime when it started and a Datetime when it ended. I also have a total of the duration. For example: suppose a job starts at 11h15 and ends at 12h15. this would mean that for hour 11 the total duration is 45 minutes. For hour 12, the duration is 15 minutes.
I thought of getting the time passed between 11h15 and 12h00 and then the time passed between 12h15 and 13h00. But I am not exactly sure how i could do this. also note that some jobs go for more than an hour and some even more than a day. I am sure there is a specific way to do this in python using timedelta. I am just not experienced enough to understand this.
This is the current code for the API end point:
class MachineDurationViewSet(APIView):
authentication_classes = (SessionAuthentication, DataAppClientTokenAuthentication)
def get(self, request):
# get names of all machines
machine_names_queryset = Machine.objects.all()
machine_names = []
for obj in machine_names_queryset:
machine_names.append(obj.name)
machine_list = {}
sum = []
queryset = Job.objects.all()
# per machine, get dur for a given hour,use names to filter
for name in machine_names:
qs_grouped_per_machine = queryset.filter(machine__name=name)
queryset_machine_start = qs_grouped_per_machine.annotate(hour=ExtractHour('dt_start'))
queryset_machine_end = qs_grouped_per_machine.annotate(hour=ExtractHour('dt_end'))
for n in range(0,24):
job_start = queryset_machine_start.filter(hour=n)
for job in job_start:
print(job.dt_start)
sum.append(job_start.count())
machine_list[name] = sum
sum = []
return Response({"machines": machine_list, "machine_count": len(machine_names)})