[Django]-Django Rest Framework: DRYer pagination for custom actions

8πŸ‘

βœ…

I don’t think we have any built-in to apply pagination on actions. But, we can have a simple decorator to do this. Make sure that your action returns a list or QuerySet when using this decorator.

from functools import wraps
from django.db.models import QuerySet

def paginate(func):

    @wraps(func)
    def inner(self, *args, **kwargs):
        queryset = func(self, *args, **kwargs)
        assert isinstance(queryset, (list, QuerySet)), "apply_pagination expects a List or a 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)
    return inner

@paginate
@action(detail=False, methods=["GET"], name="Past Objects")
def past(self, request, *args, **kwargs):
    startdate = datetime.datetime.now()
    some_user = UserProfile.objects.get(user__username="someuser")

    queryset = self.queryset.filter(
        other__attribute__profile=some_user,
        creation_date__lte=startdate
        ).order_by("-creation_date")

    return queryset

1πŸ‘

I wrote a simple function for that:

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

    return Response(viewset.get_serializer(queryset, many=True).data)

Usage is like:

@action(...)
def comments(self, ...):
    queryset = Comment.objects.filter(...)
    return response_with_paginator(self, queryset)
πŸ‘€ishak O.

Leave a comment