3

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
                )

Settings.py i have added

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

in my urls.py

router = routers.DefaultRouter(trailing_slash=False)

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

When I try with this URL http://192.168.2.66:8001/v1/voucher/country it is returning all data.

But when I am trying with this URL http://192.168.2.66:8001/v1/voucher/country/?limit=2&offset=2

but it is returning 404 error. I am new to django.kindly help me :)

4

1 回答 1

5

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

于 2017-12-12T09:25:54.170 回答