Skip to content

Commit

Permalink
feat(upgrade):pagination support for articles
Browse files Browse the repository at this point in the history
- add function in list all views to paginate articles
- import paginator from django framework

[DELIVERS #160617682]
  • Loading branch information
Amos Welike authored and AmosWels committed Oct 12, 2018
1 parent 8b1ab14 commit 2f7c993
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions authors/apps/articles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@

class ArticleAPIView(generics.ListCreateAPIView):
"""create an article, list all articles """
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from rest_framework import serializers
from django.core.exceptions import ObjectDoesNotExist
class ArticleAPIView(generics.ListCreateAPIView):
"""create an article, list all articles paginated to 5 per page"""
queryset = Article.objects.all()
permission_classes = (IsAuthenticatedOrReadOnly,)
renderer_classes = (ArticleJSONRenderer,)
Expand All @@ -28,9 +33,26 @@ def create(self, request, *args, **kwargs):
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def perform_create(self, serializer):
serializer.save(author=self.request.user)
serializer.save(author=self.request.user)

def get(self, request):
paginator = Paginator(self.queryset, 5) # show 5 articles at a time.
page = request.GET.get('page')
try:
self.queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page
self.queryset = paginator.page(1)
except EmptyPage:
# if page is out of range, deliver last page of results
self.queryset = paginator.page(paginator.num_pages)

serializer = self.serializer_class(self.queryset, many=True)
return Response({"articles": serializer.data,
"number_of_pages": paginator.num_pages,
"number_of_articles": paginator.count}, status=status.HTTP_200_OK)



class ArticleAPIDetailsView(generics.RetrieveUpdateDestroyAPIView):
"""retreive, update and delete an article """
permission_classes = (IsAuthenticatedOrReadOnly,)
Expand Down

0 comments on commit 2f7c993

Please sign in to comment.