Carlosr
Carlosr

Reputation: 28

Modify result list API django-rest-framework

I'm using django-rest-framework to create an API rest for my model, on my model I'm saving a range of dates (start and end) but on list for API I need one entry by date.

#serializers.py
class ShceduleSerializer(FlexFieldsModelSerializer):

    class Meta:
        model = Shcedule
        fields = ['id', 'start', 'end', 'user']


#viewsets.py
class ShceduleViewSet(FlexFieldsModelViewSet):

    queryset = Shcedule.objects.all()
    serializer_class = ShceduleSerializer

Now, I have something like this:

"results": [
        {
            "id": 1,
            "start": "2020-05-25",
            "end": "2020-05-29",
            "user": 50
        },

But I need a one entry by date

"results": [
            {
                "id": 1,
                "date": "2020-05-25",
                "user": 50
            },
            {
                "id": 1,
                "date": "2020-05-26",
                "user": 50
            },
            {
                "id": 1,
                "date": "2020-05-27",
                "user": 50
            },
            {
                "id": 1,
                "date": "2020-05-28",
                "user": 50
            },
            {
                "id": 1,
                "date": "2020-05-29",
                "user": 50
            },

Upvotes: 1

Views: 513

Answers (1)

Vincent
Vincent

Reputation: 1564

You can override the list() method to change the response to your needs. For example:

class ShceduleViewSet(FlexFieldsModelViewSet):

    queryset = Shcedule.objects.all()
    serializer_class = ShceduleSerializer

    def list(self, request, *args, **kwargs):
        schedule_results = super().list(request=request).data
        day_delta = datetime.timedelta(days=1)

        for schedule in schedule_results['results']:
            start_date = schedule['start']
            end_date = schedule['end']
            
            schedule_objects = {'results': []}
            for i in range((end_date - start_date).days):
                schedule_objects['results'].append({
                   "id": schedule['id'],
                   "date": start_date + i*day_delta,
                   "user": schedule['user']
                })
     
            output = schedule_objects

            return Response(output, status=status.HTTP_200_OK)

Upvotes: 2

Related Questions