Reputation: 1077
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 :)
Upvotes: 3
Views: 11790
Reputation: 6865
Use ModelViewSet
not ViewSet
. Also remove your list function it will automatically send response.
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().
UPDATE
In your settings.py
REST_FRAMEWORK = {
'PAGE_SIZE': 10,
# 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
}
UPDATE 2
Alternatively, you can just use paginate_queryset
and get_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
Upvotes: 5