amigcamel
amigcamel

Reputation: 2009

Django REST API pagination: always return the same data

Based on this tutorial, I tried to paginate a list, but failed.

Code:

views.py

@api_view(['GET'])
def test(request):
    objects = ['john', 'paul', 'george', 'ringo']
    paginator = Paginator(objects, 2)
    page = paginator.page(1)
    serializer = PaginationSerializer(instance=page, context={'request':request})
    return Response(serializer.data)

urls.py

urlpatterns = patterns('', (r'^test/$', 'ptt.views.test'))

Result:

{
    "count": 4, 
    "next": "http://localhost/test/?page=2", 
    "previous": null, 
    "results": [
        "john", 
        "paul"
    ]
}

I was expecting to get "george" and "ringo" by visiting http://localhost/test/?page=2, but I still got "john" and "paul"...

Why? What did I miss?

Upvotes: 0

Views: 740

Answers (2)

user14475872
user14475872

Reputation:

In my case, I was passing wrong argument in query param for page no. It was page but I was passing page_no

Upvotes: 0

falsetru
falsetru

Reputation: 369364

1 is hard-coded. So the first page is fetched.

page = paginator.page(1)

Use the page parameter passed:

page = paginator.page(int(request.GET.get('page', '1')))

Upvotes: 1

Related Questions