Skip to content

Commit

Permalink
feature(paginate articles): Pagination support for articles.
Browse files Browse the repository at this point in the history
- Enable users to paginate articles

[Finishes  #159952015]

Co-authored-by: huxaiphaer <huxaiphaeridris@gmail.com>
Co-authored-by: reiosantos <ronireiosantos@gmail.com>
  • Loading branch information
2 people authored and Innocent Asiimwe committed Sep 14, 2018
1 parent 4f71a57 commit ea62c3d
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 39 deletions.
7 changes: 6 additions & 1 deletion authors/apps/articles/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# Generated by Django 2.1 on 2018-09-13 09:42
# Generated by Django 2.1 on 2018-09-14 07:51

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
Expand All @@ -26,6 +30,7 @@ class Migration(migrations.Migration):
('favorited', models.BooleanField(default=False)),
('favorites_count', models.IntegerField(default=0)),
('photo_url', models.CharField(max_length=255, null=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created_at', 'author'],
Expand Down
22 changes: 0 additions & 22 deletions authors/apps/articles/migrations/0002_article_author.py

This file was deleted.

10 changes: 5 additions & 5 deletions authors/apps/articles/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ def render(self, data, accepted_media_type=None, renderer_context=None):
:param renderer_context:
:return:
"""
if isinstance(data, list) and len(data) > 1:
val = data.get("results", None)
if val and isinstance(val, list) and len(val) > 1:
return json.dumps({
'articles': data
})

if isinstance(data, list) and len(data) is 1:
data = data[0]
if val and isinstance(val, list) and len(val) is 1:
val = val[0]

if isinstance(data, list) and len(data) < 1:
data = {}
data.update({"results": val})

errors = data.get('errors', None)

Expand Down
31 changes: 30 additions & 1 deletion authors/apps/articles/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
Serializer classes for articles
"""
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination

from authors.apps.articles.exceptions import NotFoundException
from authors.apps.articles.models import Article
from authors.apps.articles.utils import get_date
from authors.apps.authentication.models import User
from authors.apps.authentication.serializers import UserSerializer
from authors.apps.profiles.models import UserProfile
from authors.apps.profiles.serializers import RetrieveUserProfileSerializer


class ArticleSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -64,7 +67,9 @@ def to_representation(self, instance):
:return:
"""
response = super().to_representation(instance)
response['author'] = UserSerializer(instance.author).data
profile = RetrieveUserProfileSerializer(UserProfile.objects.get(user=instance.author)).data

response['author'] = profile
return response

class Meta:
Expand All @@ -75,3 +80,27 @@ class behaviours
# noinspection SpellCheckingInspection
fields = ('slug', 'title', 'description', 'body', 'created_at',
'updated_at', 'favorited', 'favorites_count', 'photo_url', 'author')


class PaginatedArticleSerializer(PageNumberPagination):
"""
Pagination class
Inherits from PageNumberPagination
Paginates articles
"""
page_size = 4

def get_paginated_response(self, data):
"""
Formats response to include page links
:param data:
:return:
"""
return {
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
'count': self.page.paginator.count,
'results': data
}
10 changes: 5 additions & 5 deletions authors/apps/articles/tests/test_articles.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def test_list_specific_article(self):
self.assertIn('article', response.json())
self.assertIsInstance(response.json().get("article"), dict)

slug = response.json().get("article").get("slug")
slug = response.json().get("article").get("results").get("slug")

response = self.client.get(
"/api/articles/{0}/".format(slug), content_type='application/json')
Expand All @@ -137,7 +137,7 @@ def test_delete_specific_article(self):
self.assertIn('article', response.json())
self.assertIsInstance(response.json().get("article"), dict)

slug = response.json().get("article").get("slug")
slug = response.json().get("article").get("results").get("slug")

response = self.client.delete(
"/api/articles/{0}/".format(slug), content_type='application/json')
Expand Down Expand Up @@ -166,7 +166,7 @@ def test_list_many_articles(self):
response = self.client.get(
"/api/articles/", content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertIsInstance(response.json().get("articles"), list)
self.assertIsInstance(response.json().get("articles").get("results"), list)
self.assertEqual(len(response.json().get("articles")), 3)

def test_update_article(self):
Expand All @@ -183,7 +183,7 @@ def test_update_article(self):
self.assertIn('article', response.json())
self.assertIsInstance(response.json().get("article"), dict)

slug = response.json().get("article").get("slug")
slug = response.json().get("article").get("results").get("slug")

response = self.client.put(
"/api/articles/{0}/".format(slug), data=json.dumps(
Expand All @@ -206,7 +206,7 @@ def test_update_article_missing_data_and_not_exist(self):
self.assertIn('article', response.json())
self.assertIsInstance(response.json().get("article"), dict)

slug = response.json().get("article").get("slug")
slug = response.json().get("article").get("results").get("slug")

response = self.client.put(
"/api/articles/{0}/".format(slug), data=json.dumps(
Expand Down
12 changes: 7 additions & 5 deletions authors/apps/articles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from authors.apps.articles.exceptions import NotFoundException, InvalidQueryParameterException
from authors.apps.articles.models import Article
from authors.apps.articles.renderer import ArticleJSONRenderer
from authors.apps.articles.serializers import ArticleSerializer
from authors.apps.articles.serializers import ArticleSerializer, PaginatedArticleSerializer


# noinspection PyUnusedLocal,PyMethodMayBeStatic
Expand Down Expand Up @@ -51,12 +51,14 @@ def to_int(val):

queryset = Article.objects.all()
if queryset.count() > 0:
queryset = queryset[offset:limit]
queryset = queryset[offset:]

serializer = self.serializer_class(queryset, many=True)
data = serializer.data
data = self.serializer_class(queryset, many=True).data

return Response(data)
pager_class = PaginatedArticleSerializer()
pager_class.page_size = limit

return Response(pager_class.get_paginated_response(pager_class.paginate_queryset(data, request)))

def retrieve(self, request, slug=None):
"""
Expand Down

0 comments on commit ea62c3d

Please sign in to comment.