I would like to implement pagination in my custom jsonresponse function. But I have no idea on how would i implement this. This is the code of my function. Any inputs will be a great help. Thank you.
def json_response(data = {}, message = 'successful!', status = 'success', code = 200):
data_set = {}
status = 'success' if code == 200 else 'error'
if status == 'success':
data_set['code'] = code
data_set['status'] = status
data_set['message'] = message
# data_set['data'] = data.data
try:
data_set['data'] = data.data
except TypeError:
data_set['data'] = json.dumps(data)
except AttributeError:
data_set['data'] = data
else:
data_set['code'] = code
data_set['status'] = status
data_set['message'] = message
return JsonResponse(data_set, safe=False, status=code)
CodePudding user response:
if you're using Django Rest Framework, checkout the Pagination provided by the framework
https://www.django-rest-framework.org/api-guide/pagination/
Example:
# pagination.py
from rest_framework.pagination import PageNumberPagination
class CustomNumberPagination(PageNumberPagination):
page_size = 10 # Put the number of items you desire
# views.py
from somewhere.pagination import CustomNumberPagination
from somewhere.model import SomeModel
from somewhere.serializer import SomeSerializer
from rest_framework.generics import ListAPIView
class SomeView(generics.ListAPIView):
queryset = SomeModel.objects.all()
serializer_class = SomeSerializer
pagination_class = CustomNumberPagination
P.S. Also it can be configured globally like below
# settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10, # Put the number of items you desire
}