Ishan Khare
Ishan Khare

Reputation: 1767

django rest framework global pagination not working with ListCreateAPIView

I have the following in my settings.py

REST_FRAMEWORK = {
     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
     'PAGE_SIZE': 50
       }

urls.py

url(r'^dashboard/users$', views.UserList.as_view()),

And the View itself

class UserList(generics.ListCreateAPIView):
     queryset = User.objects.all()
     serializer_class = UserSerializer

When i try to access /dashboard/users/?page=1 I get a 404 error with the following urls in the debug mode:

^dashboard/users$
^dashboard/users\.(?P<format>[a-z0-9]+)/?$

According to the Django rest frameworks's pagination docs:

Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.

I am already using generic views here, then why doesn't this work?

Upvotes: 0

Views: 1217

Answers (2)

Ishan Khare
Ishan Khare

Reputation: 1767

Apart from the helpfull suggestion from @neverwalkaloner , I Was still seeing a 404 error. I turned out that is was due to a url missmatch

I had to change my url definition from

url(r'^dashboard/users$', views.UserList.as_view())

to

url(r'^dashboard/users/$', views.UserList.as_view())

The trailing / did the trick

Upvotes: 2

neverwalkaloner
neverwalkaloner

Reputation: 47354

From description of LimitOffsetPagination:

This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an "offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.

So you need to pass limit and offset as GET argument if you want to use LimitOffsetPagination: https://api.example.org/accounts/?limit=100&offset=400

Or you can use PageNumberPagination instead:

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100
}

Upvotes: 2

Related Questions