django - 我如何为 View 集使用限制偏移分页

标签 django django-rest-framework drf-queryset

View .py

class CountryViewSet(viewsets.ViewSet):   
    serializer_class = CountrySerializer
    pagination_class = LimitOffsetPagination
    def list(self,request):
        try:
            country_data = Country.objects.all()
            country_serializer = CountrySerializer(country_data,many=True)
            return Response(            
                data = country_serializer.data,
                content_type='application/json',            
                )
        except Exception as ex:
            return Response(
                data={'error': str(ex)},
                content_type='application/json',
                status=status.HTTP_400_BAD_REQUEST
                )

设置.py 我已经添加了

'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',

在我的 urls.py 中

router = routers.DefaultRouter(trailing_slash=False)

router.register(r'country', CountryViewSet, base_name='country')
urlpatterns = [
    url(r'^', include(router.urls)),
]

当我尝试使用此 URL http://192.168.2.66:8001/v1/voucher/country 时它正在返回所有数据。

但是当我尝试使用此 URL http://192.168.2.66:8001/v1/voucher/country/?limit=2&offset=2

但它返回 404 错误。 我是 django 的新手。请帮助我 :)

最佳答案

使用ModelViewSet不是 ViewSet。同时删除您的列表功能,它将自动发送响应。

from rest_framework.pagination import LimitOffsetPagination

class CountryViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing country.
    """ 
    queryset = Country.objects.all()
    serializer_class = CountrySerializer
    pagination_class = LimitOffsetPagination

The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().

更新

在你的 settings.py 中

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

更新 2

或者,您可以只使用 paginate_querysetget_paginated_response

def list(self,request):
    country_data = Country.objects.all()

    page = self.paginate_queryset(country_data)
    if page is not None:
       serializer = self.get_serializer(page, many=True)
       return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(country_data, many=True)
    return Response(serializer.data)

Reference: marking-extra-actions-for-routing

关于django - 我如何为 View 集使用限制偏移分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47768882/

相关文章:

django.db.utils.ProgrammingError : relation "auth_permission" does not exist

python - 如何配置 wsgi 应用程序迁移到 django 1.7?

python - Django 多个媒体字段未上传到 S3

django - 如何在 JSONField 上使用 django-filter

Django - 如何在 ManyToMany 字段查询集上设置默认排序

django - 将 Django 查询对象 value() 传递到 Django Rest Framework Serializer

django - 尝试将 QuerySet 作为初始数据传递给表单集

reactjs - 在 Axios 中的 GET 方法 URL 搜索参数中发送嵌套对象

django - 使用直通模型了解 Django 中的多对多字段