普拉多VX

人生一路,不问来时,不知归期

0%

drf 框架自定义分页代码

1.重写分页 utils/Page文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination
from collections import OrderedDict
from rest_framework.response import Response


class StandardResultsSetPagination(PageNumberPagination):
page_size = 20
page_size_query_param = 'pageSize'
max_page_size = 2000
page_query_param = "pageNo" # 定制请求参数为pageNo

def get_paginated_response(self, data):
return Response(OrderedDict([
('totalCount', self.page.paginator.count),
('pageNo', self.page.number),
('pageSize', self.get_page_size(self.request)),
('totalPage', self.page.paginator.num_pages),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('code', 0),
('message', 'Ok'),
('data', data), # 返回的data标示
]))

2.配置settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
REST_FRAMEWORK = {
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60,

'DEFAULT_PAGINATION_CLASS': 'utils.Page.StandardResultsSetPagination',

'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),

'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
)
}

3.访问结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"totalCount": 1151, //总数据条数
"pageNo": 2, //当前分页
"pageSize": 3, //分页大小
"totalPage": 384, //分页数
"next": "http://127.0.0.1:8001/api/users/?pageNo=3&pageSize=3",
"previous": "http://127.0.0.1:8001/api/users/?pageSize=3",
"code": 0,
"message": "Ok",
"data": [
{
"username": "xxxx",
"mobile": "xxxxxx",
"email": "xxxx@qq.com",
"date_joined": "2019-04-25 13:44:47",
"last_login": "2019-04-27 10:00:44"
},
{
"username": "roddytest",
"mobile": "",
"email": "xxxx@qq.com",
"date_joined": "2019-04-26 15:50:27",
"last_login": "2019-07-06 19:33:54"
},
{
"username": "xxxx",
"mobile": "",
"email": "xx@qq.com",
"date_joined": "2019-04-29 11:30:22",
"last_login": "2020-01-12 06:17:14"
}
]
}