1

friends,

After some python scripting I get below response in Django using POST method:

[{'ID': 76544,
      'Location': 'NM, USA',
      'Location_score': 0.7142857142857143,
      'No_of_matched_comp': 3,
      'No_of_matched_industry': 3,
      'over_all_score': 91,
      'title': 'Accounting',
      'title_score': 1.0},
     {'ID': 76545,
      'Location': 'NM, USA',
      'Location_score': 0.7142857142857143,
      'No_of_matched_comp': 3,
      'No_of_matched_industry': 3,
      'over_all_score': 91,
      'title': 'Accounting',
      'title_score': 1.0},
     {'ID': 55557,
      'Location': 'CO, USA',
      'Location_score': 0.7142857142857143,
      'No_of_matched_comp': 2,
      'No_of_matched_industry': 2,
      'over_all_score': 74,
      'title': 'Account',
      'title_score': 0.8235294117647058}]

Count is 50 so I want to 10 data per page from Response. Now I want to paginate this Response. my input parameters Different from Output parameters.

input parameters model.py is below:

class TalentSearchInput(models.Model):
    Date = models.CharField(max_length = 100,blank=True, null=True)
    Title = models.CharField(max_length = 100)
    Location = models.CharField(max_length = 100)
    Competency_user = models.CharField(max_length = 100,blank=True, null=True)
    Comp_ID = ArrayField(ArrayField(models.IntegerField()))
    Day_rate_lower = models.IntegerField(blank=True, null=True)
    Day_rate_upper = models.IntegerField(blank=True, null=True)
    hourly_rate_lower = models.IntegerField(blank=True, null=True)
    hourly_rate_upper = models.IntegerField(blank=True, null=True)
    Industry_ID = ArrayField(ArrayField(models.IntegerField()),blank = True, null = True)

    def __str__(self):
        return self.title

How to do pagination in Django REST API in APIView?

I gone through following links:

http://www.django-rest-framework.org/api-guide/pagination/#limitoffsetpagination

https://docs.djangoproject.com/en/dev/topics/pagination/

Django Rest Framework 3.1 breaks pagination.PaginationSerializer

My View.Py file as below:

from django.shortcuts import render

# Create your views here.
import json
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import TalentSearchInput, EmployerInput, SearchFilter#, TalentScoring
from .serializers import TalentSearchSerializer, EmployerSerializer, FilterSerializer,TalentScoringSerializer
#from rest_framework.pagination import PageNumberPagination
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
#from django.shortcuts import render
#from base_searchAPP.pagination import CustomPagination

#from rest_framework.settings import api_settings
#from base_searchAPP.mixin import MyPaginationMixin

#Python Code Modules
import pandas as pd
import numpy as np
import MySQLdb
import MySQLdb.cursors
import json
import os
from difflib import SequenceMatcher as SM
from nltk.util import ngrams
import codecs
from collections import defaultdict

# Talent Search Views
@api_view(['GET', 'POST'])
#@permission_classes([AllowAny,])
def TalentInputparameters_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        print('GET.call')
        #print(Snippet)
        TalentSearch = TalentSearchInput.objects.all()
        serializer = TalentSearchSerializer(TalentSearch, many=True)
        print(serializer)
        d = Response(serializer.data)
        return d

    elif request.method == 'POST':
            print('POST.call')
            # Input Data
            d = request.data
            print(d)
            #Input Python code Here
            # Load Json into python
            #d = json.loads(d)

This is part of file I am using this method.

I tried to insert following lines in setting.py file as per first link suggestion for Globally pagination

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE' : 10
}

please advice me my Output parameters are different so should I make Model and Serializers for output parameters?

if yes then

when I add model and serializer class in view.py file where should I add my Response so it will paginate?

Thank you so much.

If my Question is not properly please forgive me and let me know if anyone need more information

Pmsheth
  • 176
  • 1
  • 13

4 Answers4

6

Thank you so much for your kind answers. But It resolved by follow code:

I created Model for output parameters like below in model.py file:

class TalentScoring(models.Model):
    ID = models.IntegerField(blank=True, null=True)
    title = models.CharField(max_length = 100)
    Location = models.CharField(max_length = 100)
    Location_score = models.IntegerField(blank=True, null=True)
    No_of_matched_comp = models.IntegerField(blank=True, null=True)
    No_of_matched_industry = models.IntegerField(blank=True, null=True)
    over_all_score = models.IntegerField(blank=True, null=True)
    title_score = models.IntegerField(blank=True, null=True)

I have done serializer for this model also like below so it will serialize my response and give output my serializer.py file is blow:

class TalentScoringSerializer(serializers.ModelSerializer):

    class Meta:
        model = TalentScoring
        fields = ('ID','title','Location','Location_score','No_of_matched_comp','No_of_matched_industry','over_all_score','title_score')

view.py file as below

from rest_framework.pagination import PageNumberPagination

paginator = PageNumberPagination()

paginator.page_size = 10

result_page = paginator.paginate_queryset(final_Score, request)

serializer = TalentScoringSerializer(result_page, many=True)

return paginator.get_paginated_response(serializer.data)

My list name is "final_Score" after done some python coding on input parameters Now I can show 10 data per page as per my desire.

Pmsheth
  • 176
  • 1
  • 13
1

You can use Django Paginator for this. For More

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

TalentSearch = TalentSearchInput.objects.all()
paginator = Paginator(TalentSearch,items_per_page)
page_num = 1

try:
    TalentSearch = paginator.page(page_num)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    TalentSearch = paginator.page(1)
except EmptyPage:
    # If page is out of range, deliver last page of results.
    TalentSearch = paginator.page(paginator.num_pages)

serializer = TalentSearchSerializer(TalentSearch, many=True)
d = Response(serializer.data)
return d

Hope it will help.

vermanil
  • 212
  • 1
  • 8
  • Thank you for your kind reply. But my Final Response is different That I shown in Question I want to Paginate that Response. Like it giving me 50 data now I want to paginate that 10 Data per page. and Model parameters and Response parameters are different so should I make model for Response parameters? Please advice me I am new in Django. – Pmsheth Jun 15 '18 at 04:57
  • Did you try that? – vermanil Jun 15 '18 at 05:05
  • yes it giving me error: 'page_num' is not define. I pass serializer also like below: `serializer = TalentSearchSerializer(TalentSearch, many = True)` – Pmsheth Jun 15 '18 at 05:39
  • initialize page_num t0 any number like page_num=1 – vermanil Jun 15 '18 at 05:41
  • I did that but It gives me below error: `AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a ``` I edited my Question can you please look it again Thank you so much for kind replies – Pmsheth Jun 15 '18 at 05:44
  • Thanks for reply but it gives me blank list because I am not passing anywhere my output after some python scripting in Pagination can you please suggest me how to pass it or where can I pass? – Pmsheth Jun 15 '18 at 06:00
0

you can try this :

from django.core.paginator import Paginator

size = 10
page = request.GET.get('page')
paginator = Paginator(TalentSearch, size)
resources = paginator.get_page(page)
serializer = TalentSearchSerializer(resources, many=True)
return Response(serializer.data)

other example maybe find in here

https://docs.djangoproject.com/en/2.0/topics/pagination/

Pradip Kachhadiya
  • 2,067
  • 10
  • 28
Ngoc Pham
  • 1,408
  • 9
  • 18
  • Thanks for you reply I edited my Question so Now you can know where am i stuck. I tried your code but it gives me error: name 'page' is not define – Pmsheth Jun 15 '18 at 05:34
0

using the class base view you can do like this

from rest_framework.pagination import PageNumberPagination
from rest_framework import generics

class TalentSearchpagination(PageNumberPagination):
    page_size = 10

class BlogListing(generics.ListAPIView):
    pagination_class = TalentSearchpagination
    serializer_class = TalentSearchSerializer

    def get_queryset(self):
        TalentSearch = TalentSearchInput.objects.all()
        return TalentSearch
Pawanvir singh
  • 373
  • 6
  • 17