I'm super new to django and the rest API framework. I have a project that I am working on using both and vueJS for the front end. I need to serialize some data for a chart.
For one of the API end points I am trying to group the data like so:
"day_of_the_week": {
"9am":[{"job":".."}],
"10am":[{"job":"..."}],
"11am": [{"job": ".."}],
...
}
I am using a Job class, for reference this is how the jobs end point looks like: jobs-api
So instead of what i have on the picture I am creating a new endpoint where i will only show one object that contains the data for any given day. On the front end there is a chart with filters that let the user filter the jobs by the day they request. On load, when the user has given no day of the week, the end point will return the object of 'today'.
Because I am new to this, I have no idea where to do this, my initial thought was to filter on the views.py, but for now I have done it in the serializer which gives me the error "Object of type Job is not JSON serializable".
This is how the serializer looks like: jobs-by-day-serializer
Clearly, there is something that I am not quite grasping, so any help would be appreciated.
EDIT: this is my views.py now, I have added the filter for the queryset to filter by day, so I can filter by day now: jobs_by_day_viewset
The answers given provides a solution for one part of the question. I managed to solve the second part. Once I could filter my queryset by day of the week I still had to group every object by the hour in which it had been started. This is how i solved it:
def get(self, request):
params = self.get_params()
queryset = Job.objects.filter(
dt_start__week_day=params['day'], dt_start__gte=params['dt_start'], dt_end__lte=params['dt_end'])
queryset_started = queryset.annotate(hour=ExtractHour('dt_start'))
queryset_ended = queryset.annotate(hour=ExtractHour('dt_end'))
started = []
ended = []
total_jobs =[]
for n in range(0, 23):
queryset_end = queryset_ended.filter(hour=n)
ended.append(round(queryset_end.count() / queryset.count() * 100, 2))
queryset3 = queryset_started.filter(hour=n)
started.append(round(queryset3.count() / queryset.count() * 100, 2))
for x in range(len(started)):
total_jobs.append(round(started[x]+ended[x], 2))
I used a viewset that extended from APIview instead of the modelviewsets so that i was able to return an array of integers.