Kioko Kiaza
Kioko Kiaza

Reputation: 1398

django-rest-framework, how to paginate

This is my view witch works ok:

from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import serializers
from gamerauntsia.berriak.serializers import BerriaSerializer
from rest_framework.response import Response
import json



class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def app_berria_list(request):
    if request.method == 'GET':
        berriak = Berria.objects.all()
        serializer = BerriaSerializer(berriak, many=True)
        return JSONResponse(serializer.data)

I want the response paginated by 5 items, so I tried adding this in settings.py:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 5
}

Do I need to change something more to make it work? Thanks in advance

Upvotes: 0

Views: 1587

Answers (1)

Collin Reynolds
Collin Reynolds

Reputation: 397

Serializers don't paginate by themselves, you have to call the pagination class with the queryset as an argument. The built-in rest_framework.viewsets.ModelViewSet will do both the JSON parsing/rendering and pagination by default without you having to do anything.

Why not have a viewset class such as:

from rest_framework import viewsets
class BerriaViewSet(viewsets.ModelViewSet):
    queryset = Berria.objects.all()
    serializer_class = BerriaSerializer

This will do everything you want I believe.

If you insist on doing it the way you are, however, you can do the following:

from rest_framework.pagination import PageNumberPagination
@csrf_exempt
def app_berria_list(request):
    if request.method == 'GET':
        berriak = Berria.objects.all()
        paginator = PageNumberPagination()
        page = paginator.paginate_queryset(berriak, request)
        serializer = BerriaSerializer(page, many=True, context={'request': request})
        return paginator.get_paginated_response(serializer.data)

Upvotes: 3

Related Questions