[Fixed]-How to process current page of records in Django REST?

1👍

Maybe there is a better solution, but I had to roll out my own View class to do post processing after the queryset is filtered and paginated but before it is serialized:

class DecoratedListModelMixin(object):
    """
    Apply a decorator to the list view before serializing
    """
    def list(self, request, *args, **kwargs):
        has_decorator = (hasattr(self, 'decorator') and self.decorator is not None)

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

        if page is not None:

            if has_decorator:
                serializer = self.get_serializer(self.decorator(page, request), many=True)
            else:
                serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        if has_decorator:
            serializer = self.get_serializer(self.decorator(queryset, request), many=True)
        else:
            serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

class DecoratedListAPIView(DecoratedListModelMixin, generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

Usage:

class FooView(DecoratedListAPIView):
    serializer_class = FooSerializer
    pagination_class = FooPagination
    decorator = foo_decorator
    def get_queryset(self):
        user = self.request.user
        return Foo.objects.filter(bar=true, user=user).order_by('created')

# queryset contains current page only
def foo_decorator(view, queryset, request):
    for foo in queryset:
        #...
    return queryset
👤serg

Leave a comment