Skip to content
Advertisement

Serialize a M-2-M relation with grouping in Django REST framework

I have two models, linked through a separate model as follow:

JavaScript

Serialized is pretty straight forward:

JavaScript

A viewset returns the total number of houses assigned to each employee for different projects, summed over dates:

JavaScript

In the output we have multiple records for each employee:

JavaScript

I want to convert it to a nested list so that the booked hours show up as a list for each employee. I checked multiple threads, but couldn’t find a reasonable solution. I think it’s possible to convert it to a grouped dataframe and output as JSON, but it wouldn’t be part of the Django Rest framework.

As far as I know, Django ORM doesn’t support nested queryset. Is there a workaround for that?

Advertisement

Answer

You can create a EmployeeSerializer with a nested serializer with Schedule.

First, to improve reading, you should add a related name to schedule

JavaScript

To have the booked hours, you can update the model :

JavaScript

and then in the serializer

JavaScript

Thanks to that, you will have :

JavaScript

To optimize the queryset, you should not forget to use prefect_related. The viewset will be :

JavaScript

ReadOnlyModelViewSetis doing the rest of the job here.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement