Home > Software design >  How to use Filterset and paginateion in ApiView?
How to use Filterset and paginateion in ApiView?

Time:11-17

I am trying to use PageNumberPagination and FilterSet in APIView. But I have an error below in my code.

object of type 'ListSerializer' has no len()

How to implement this?


Here are the code:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'


class MyFilter(filters.FilterSet):
    class Meta:
        model = MyModel
        fields = '__all__'


class MyAPIView(views.APIView, PageNumberPagination):

    def get(self, request, *args, **kwargs):
        filterset = MyFilter(request.query_params, queryset=MyModel.objects.all())

        if not filterset.is_valid():
            raise ValidationError(filterset.errors)

        serializer = MySerializer(instance=filterset.qs, many=True)
        paginate_queryset = self.paginate_queryset(serializer, request, view=self)

        return Response(paginate_queryset.data)

Django 3.2.6

django-filter 22.1

djangorestframework 3.12.4

Python 3.8

CodePudding user response:

You should not try to make your object inherit from APIView and PageNumberPagination, as one is a view, and the other one, a paginator.
If you want to keep your code as simple as possible, just use a ListAPIView:

class MyAPIView(ListAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MySerializer
    filterset_class = MyFilter
    pagination_class = PageNumberPagination

If you want to get this pagination as the default one, you can even set it as the default pagination style once so you don't have to define it in each of the views that use it.

CodePudding user response:

Apply Pagination on ApiView

views.py

from rest_framework.pagination import PageNumberPagination
class EventNewsItems(APIView, PageNumberPagination):
    def get(self, request, pk, format=None):
        event = Event.objects.get(pk=pk)
        news = event.get_news_items().all()
        results = self.paginate_queryset(news, request, view=self)
        serializer = NewsItemSerializer(results, many=True)
        return self.get_paginated_response(serializer.data)
  • Related