【问题标题】:How can i use limit offset pagination for viewsets我如何为视图集使用限制偏移分页
【发布时间】:2018-05-25 22:01:46
【问题描述】:

Views.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 的新手。请帮助我:)

【问题讨论】:

  • 您肯定会得到 404,因为您设置了 trailing_slash=False 但您在 URL 中使用了斜杠。这与偏移量无关。

标签: django django-rest-framework drf-queryset


【解决方案1】:

使用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

ModelViewSet类提供的动作是.list(), .retrieve()、.create()、.update()、.partial_update() 和 .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)

参考: marking-extra-actions-for-routing

【讨论】:

  • 如果我使用 ModelViewSet,那么我可以使用 list(),retrieve(),create(),update(),destroy() 选项吗?
  • 我仍然面临同样的问题。 :(
  • 你需要在你的settings.py中设置PAGE_SIZE
  • 检查我的更新尝试创建另一个分页类并在视图集中使用该类。
  • @SusajSNair,这行得通吗?也看看 DanielRoseman 的评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 2014-08-26
相关资源
最近更新 更多