3

Everything is imported, it might not be working because of get_queryset function, but i am not sure.

class ShowStats(ListAPIView):
    serializer_class = StatsSerializer

    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    ordering_fields = ('date', 'views', 'clicks', 'cost', 'cpc', 'cpm')
    ordering = ('views',)

    def get_queryset(self):
        return Stats.objects.filter(date__range=[self.kwargs['from'], self.kwargs['to']])

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        response_list = serializer.data
        for i in range(len(response_list)):
            response_list[i]['cpc'] = response_list[i]['cost'] / response_list[i]['clicks']
            response_list[i]['cpm'] = response_list[i]['cost'] / response_list[i]['views'] * 1000
        return Response(data=response_list)

1 Answer 1

3

Change

queryset = self.get_queryset()

to

queryset = self.filter_queryset(self.get_queryset())

to apply filtering and/or ordering.


Here's what DRF's ListModelMixin looks like (for inspiration).

class ListModelMixin:
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.