如何在Django中实现分页

How to implement pagination in Django

我想在我的自定义 jsonresponse 函数中实现分页。但我不知道我将如何实现这一点。这是我的函数的代码。任何输入都会有很大的帮助。谢谢。

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)

如果您使用的是 Django Rest Framework,请检查框架提供的分页

https://www.django-rest-framework.org/api-guide/pagination/

示例:

# 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。也可以像下面这样全局配置

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10, # Put the number of items you desire 
}