美文网首页
rest_framework 分页

rest_framework 分页

作者: eeert2 | 来源:发表于2020-02-28 21:51 被阅读0次

django一样,rest_framework也有自己的分页器,且rest_framework的分页器是基于django的分页器。

rest_framework的分页器较django的便捷之处是使用方便,只需要配置一次即可。

1. PageNumberPagination 分页器使用

PageNumberPagination分页器通过指定页数条目来完成分页,如:

http://api.example.org/accounts/?page=4

http://api.example.org/accounts/?page=4&page_size=100

PageNumberPagination常用属性:

class PageNumberPagination(BasePagination):
    page_size = api_settings.PAGE_SIZE # 设置每页的条目数
    page_query_param = 'page' # 设置查询页码的关键字参数
    page_size_query_param = None #  设置查询条目数的关键字参数
    max_page_size = None # page_size的最大值

example 1. 继承PageNumberPagination 重写参数,并简单使用

# models.py
from django.db import models


class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
# views.py
from rest_framework.views import APIView
from rest_framework import serializers
from my_app.models import UserInfo
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

class MyPagePagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    max_page_size = 30


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = '__all__'


class UserInfoView(APIView):

    def get(self, request, *args, **kwargs):
        paginator = MyPagePagination()
        queryset = UserInfo.objects.all() # 获取查询结果集

        # 将查询结果集按照 `page` / `size` 进行分页
        paginate_queryset = paginator.paginate_queryset(
            queryset=queryset,
            request=request,
            view=self
        )
        # 将分页后的查询结果集进行序列化
        serializer = UserSerializer(paginate_queryset, many=True)
        return Response(serializer.data)
# urls.py

from django.contrib import admin
from django.urls import path
from my_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/users/', views.UserInfoView.as_view()),
]

访问 :http://127.0.0.1:8000/api/users?page=1获取:

[
    {
        "id": 1,
        "username": "韩美美",
        "password": "hmmhf45-s"
    },
    {
        "id": 2,
        "username": "李乐",
        "password": "94#jd"
    }
]

也可以通过size=来改变显示条目数 http://127.0.0.1:8000/api/users?page=1&size=3

[
    {
        "id": 1,
        "username": "韩美美",
        "password": "hmmhf45-s"
    },
    {
        "id": 2,
        "username": "李乐",
        "password": "94#jd"
    },
    {
        "id": 3,
        "username": "王昭君",
        "password": "sdf097^-sdf"
    }
]

LimitOffsetPagination分页器使用

LimitOffsetPagination是通过设置起始条目条目数来实现分页,如:

http://api.example.org/accounts/?limit=100

http://api.example.org/accounts/?offset=400&limit=100
class LimitOffsetPagination(BasePagination):
    default_limit = api_settings.PAGE_SIZE # 显示的每页条目数
    limit_query_param = 'limit' # 设置查询每页条目的关键字参数
    offset_query_param = 'offset' # 设置查询起始条目的关键字参数
    max_limit = None # 设置每页的条目最大长度

example 2. 使用 LimitOffsetPagination

from rest_framework.views import APIView
from rest_framework import serializers
from my_app.models import UserInfo
from rest_framework.response import Response
from rest_framework.pagination import LimitOffsetPagination


class MyPagePagination(LimitOffsetPagination):
    default_limit = 2
    max_limit = 3


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = '__all__'


class UserInfoView(APIView):

    def get(self, request, *args, **kwargs):
        paginator = MyPagePagination()
        queryset = UserInfo.objects.all()
        paginate_queryset = paginator.paginate_queryset(
            queryset=queryset,
            request=request,
            view=self
        )
        serializer = UserSerializer(paginate_queryset, many=True)
        return Response(serializer.data)

访问:http://127.0.0.1:8000/api/users?offset=1&limit=3

[
    {
        "id": 2,
        "username": "李乐",
        "password": "94#jd"
    },
    {
        "id": 3,
        "username": "王昭君",
        "password": "sdf097^-sdf"
    },
    {
        "id": 4,
        "username": "李诗诗",
        "password": "sdj875*"
    }
]

相关文章

网友评论

      本文标题:rest_framework 分页

      本文链接:https://www.haomeiwen.com/subject/xfwrhhtx.html