DRF分页

一、序列化

1 from  rest_framework impost serializers
2 from . models import *
3 
4 class GoodsSerializer(serializers,ModelSerializer):
5     """商品序列化"""
6     class Meta:
7         model=Goods
8         fields="__all__"
serializers.py

二、分页代码

 1 from rest_framework.views import APIView
 2 from rest_framework.response import Response
 3 from django.core.paginator import Paginator 
 4 from .serializer import GoodsSerializer
 5 from django.core.paginator import Paginator, EmptyPage, InvalidPage
 6 
 7 class GoodsPageApi(APIView):
 8     """
 9     分页
10     """
11     def get(self, request, pindex):
12         # 1、获取商品信息
13         goods_list = Goods.objects.all()
14         # 2、实例化分页器
15         paginat = Paginator(goods_list, 2)
16         # 3、 获取分页
17         paged = paginat.page(pindex)
18         try:  # 判断是否有下一页
19             paged.has_next()
20             down_page = paged.next_page_number()  # 获取一下页的页码
21         except EmptyPage:  # 如果下一页为空的话,
22             down_page = paged.paginator.num_pages  # 获取最后一页的页码
23             paged = paginat.page(down_page)
24 
25         try:
26             paged.has_previous()  # 判断是否有上一页
27             up_page = paged.previous_page_number()  # 获取上页的页码
28         except InvalidPage:  # 如果没有上一页
29             up_page = 1  # 返回第一页
30             paged = paginat.page(up_page)
31 
32         # 4、 做序列化
33         page_serializer = GoodsSerializer(paged, many=True)
34 
35         # 5、 返回数据
36         return Response({
37             'code': 200,
38             'data': page_serializer.data,
39             'page_list': [i for i in paginat.page_range],
40             'has_previous': paged.has_previous(),  # 判断是否有上一页
41             'has_next': paged.has_next(),  # 判断是否有下一页
42             'previous_page_number': up_page,  # 返回上一页的页码
43             'next_page_number': down_page,  # 返回下一页的页码
44             'page_number': paged.number  # 返回当前页页码
45         })
views.py

三、urls.py

path('goods_page/', views.GoodsPageApi.as_view()),  # 商品分页

四、vue分页展示



View Code

你可能感兴趣的:(DRF分页)