首页 > 其他分享 >restframework分页组件的应用

restframework分页组件的应用

时间:2022-10-15 11:57:17浏览次数:55  
标签:分页 get self queryset LimitOffsetPagination restframework 组件 pager response

restframework中提供了优秀的分页组件

settings.py中,填写关于restframework的配置

REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
    "PAGE_SIZE": 4
}

1.PageNumberPagination

from rest_framework.pagination import LimitOffsetPagination
class BlogView(APIView):
    authentication_classes = [BlogAuthentication, ]

    def get(self, request, *args, **kwargs):
        """ 博客列表 """
        # 1.读取数据库中的博客信息
        queryset = models.Blog.objects.all().order_by("id")
        from rest_framework.pagination import LimitOffsetPagination
        pager = LimitOffsetPagination()
        res = pager.paginate_queryset(queryset, request, self)
        # total_res = pager.get_paginated_response()
        # 2.序列化
        ser = BlogSerializers(instance=res, many=True)
        response = pager.get_paginated_response(ser.data)
        # 3.返回
        return response
# 获取到所有queryset对象
queryset = models.Blog.objects.all().order_by("id")
from rest_framework.pagination import PageNumberPagination
# 实例化分页对象&传入参数(数据queryset,request对象,view)
pager = PageNumberPagination()
res = pager.paginate_queryset(queryset, request, self)
ser = BlogSerializers(instance=res, many=True)
response = pager.get_paginated_response(ser.data)
return response  
  • return response

这里的response经过了get_paginated_response方法的封装,具体过程:

class LimitOffsetPagination(BasePagination):
    ...
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ]))

get_paginated_response在返回时调用了restframework的response,

并且封装了更多的与分页相关的参数返回给调用它的API,

如果希望对封装的参数进行自定制,或者增加一些其他的参数,

可以写一个子类MyLimitOffsetPagination并且

重写get_paginated_response(self, data)方法

class MyLimitOffsetPagination(LimitOffsetPagination):
    ...
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('xxx',self.xxx)
            ('count', self.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ]))

image

{
    "count": 15,
    "next": "http://127.0.0.1:8000/api/blog/?limit=4&offset=4&page=2",
    "previous": null,
    "results": [
        {
            "id": 1,
            "category": "云计算",
            "image": "xxxx/xxxxx.png",
            "title": "郑经理",
            "summary": "....",
            "ctime": "2022-10-01",
            "comment_count": 0,
            "favor_count": 0,
            "creator": {
                "id": 1,
                "username": "wupeiqi"
            }
        },
        {
            "id": 2,
            "category": "Python全栈",
            "image": "xxxx/xxxxx.png",
            "title": "震惊了",
            "summary": "....",
            "ctime": "2022-10-01",
            "comment_count": 0,
            "favor_count": 0,
            "creator": {
                "id": 2,
                "username": "cxr"
            }
        },
        ......
    ]
}

2.LimitOffsetPagination

from rest_framework.pagination import LimitOffsetPagination
class BlogView(APIView):
    authentication_classes = [BlogAuthentication, ]

    def get(self, request, *args, **kwargs):
        """ 博客列表 """
        # 1.读取数据库中的博客信息
        queryset = models.Blog.objects.all().order_by("id")
        from rest_framework.pagination import LimitOffsetPagination
        pager = LimitOffsetPagination()
        res = pager.paginate_queryset(queryset, request, self)
        # total_res = pager.get_paginated_response()

        # 2.序列化

        ser = BlogSerializers(instance=res, many=True)
        response = pager.get_paginated_response(ser.data)
        # 3.返回
        return response
    ......

LimitOffsetPagination更加适合滚动翻页的情况

LimitOffsetPagination,滚动翻页
	/accounts/?offset=2&limit=10
	/accounts/?offset=10&limit=10

	/accounts/?lastid=10&offset=0&limit=10
	/accounts/?lastid=20&offset=0&limit=10

标签:分页,get,self,queryset,LimitOffsetPagination,restframework,组件,pager,response
From: https://www.cnblogs.com/uichuan/p/16793819.html

相关文章

  • restframework序列化的应用
    序列化器有两个功能数据校验序列化1.序列化器的简单实用序列化器将django通过orm操作从数据库中取得的数据做序列化操作转换为Json数据需要编写序列化类fromapii......
  • Jmeter扩展组件:图形监视器-PerfMon (Servers Performance Monitoring)
    1、是什么用于监听服务器CPU、IO、网络等各项指标的组件2、如何实现Jmeter​本身不具备该功能,需要下载第三方实现在服务器端安装监听程序,在测试机端安装接收程序监听程序:Ser......
  • vue-preview图片预览组件的使用
    一、运行命令`npmivue-preview `安装插件。二、在main.js里面进行全局声明。 三、插入缩略图,imgs1为定义的用于存储缩略图数据的属性。   四、获取数据......
  • Jmeter组件:组件执行顺序和作用域
    1、组件执行顺序组件:Jmeter的内置功能,每一个功能都是一个组件元件:元件中存储的都是性质相似的组件(就是对组件的分类管理)各组件之间的排序配置原件(configelements):存储了一些......
  • Elasticsearch使用terms聚合之后进行分页排序
    引言elasticsearch中实现聚合也非常常见,同时es的数据量一般比较大,因此聚合结果比较多,像terms聚合默认只返回10条聚合结果,所以聚合之后进行分页,也是非常常见的操作。es的t......
  • 组件化的额外补充
    1.$refs的使用在使用vue框架的时候,尽量不要去操作原生的DOM但是某些情况下,在组件中想要直接获取到元素对象或者子组件实例,vue提供了$refs1.1获取元素点击查看代......
  • uni-app 148朋友圈列表分页功能实现
    下图是我测试的截图/pages/find/moments/moments.vue<template><view><free-transparent-bar:scrollTop="scrollTop"@clickRight="clickRight"></free-transparent-......
  • 组件上的 v-model
    ......
  • uni-app 4.7封装头像组件
    创建free-avart.vue文件<template><image:src="src"mode="widthFix":style="getStyle":class="type"></image></template><script>exportdefault{props:{......
  • uni-app 4.10封装聊天列表组件
    聊天组件free-media-list.vue,如下代码<template><viewhover-class="bg-light"><divclass="flexalign-stretch"><viewclass="flexalign-centerjustify-c......