django rest 框架全局分页不适用于 ListCreateAPIView

django rest framework global pagination not working with ListCreateAPIView

我的 settings.py

中有以下内容
REST_FRAMEWORK = {
     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
     'PAGE_SIZE': 50
       }

urls.py

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

以及视图本身

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

当我尝试访问 /dashboard/users/?page=1 时,我在调试模式下得到一个 404 error,其中包含以下网址:

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

根据 Django 休息框架的 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.

我已经在这里使用了通用视图,那为什么它不起作用?

来自 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.

所以如果你想使用LimitOffsetPagination,你需要传递limitoffset作为GET参数:https://api.example.org/accounts/?limit=100&offset=400

或者您可以使用 PageNumberPagination 代替:

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

除了@neverwalkaloner 的有用建议,我仍然看到 404 错误。我发现这是由于 url 不匹配

我不得不更改我的 url 定义

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

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

The trailing / did the trick