django rest_framework vue 实现用户列表分页
后端
配置urls
# 导入view
from api.appview.userListView import userListView # 增加url配置
urlpatterns = [ ...
url(r'^home/userlist/$', userListView.as_view()), # 用户列表
]
编写视图
# FileName : userListView.py
# Author : Adil
# DateTime : 2019/8/2 1:46 PM
# SoftWare : PyCharm from api import models
from django.http import JsonResponse
from rest_framework.views import APIView from api.models import User
from api.utils.auth import Authentication
from api.common.PageHandle import MyLimitOffsetPagination
from rest_framework import serializers class userListView(APIView): authentication_classes = [Authentication] # 添加认证
permission_classes = [] # 不尽兴权限控制 def get(self,request,*args,**kwargs): # user1 = models.User.objects.all()
#
# print(user1) # <QuerySet [<User: username: wang,password: 123456>,... # userInfoList = models.User.objects.values() # print('^^^^^')
# for userlist in userInfoList:
#
# # userlist = model_to_dict(userlist)
# print(type(userlist))
# print(userlist) # print(type(userInfoList))
# print("!!!!!")
# userInfoList = model_to_dict(userInfoList)
#
# print(type(userInfoList)) # print(userInfoList) # <QuerySet [{'id': 1, 'username': 'wang', 'password': '123456', 'age': '20', 'e_mail': '272981562@qq.com', 'user_type': 2, 'create_time': datetime.datetime(2019, 7, 30, 21, 16, 12, 301365), 'update_time': datetime.datetime(2019, 7, 30, 21, 16, 12, 301396)}, {'id': 2, ... # for userList in userInfoList:
# #print(userList) # users = models.User.objects.values_list()
# print("8***")
# print(users) # <QuerySet [(1, 'wang', '123456', '20', '272981562@qq.com', 2, datetime.datetime(2019, 7, 30, 21, 16, 12, 301365), datetime.datetime(2019, 7, 30, 21, 16, 12, 301396)), (2, 'yang', '....
# for user in users:
# print(user) userInfoList = models.User.objects.values()print(userInfoList) ret = {'code': 1000, 'msg': None, 'data': None,'lens':None}
try:
ret['msg'] = '成功'
ret['data'] = list(userInfoList)
ret['lens'] = len(userInfoList)
except Exception as e:
ret['code'] = 1001
ret['msg'] = '失败' return (JsonResponse(ret))
# return (page.get_paginated_response(roles_ser.data))
至此完成后端code。
查看接口返回
可以看到此时返回的是查询所有结果,有21条数据。
可以看到 这样返回的结果是21条数据,而不能分页展示。
下面介绍一下分页功能
创建分页类
# FileName : PageHandle.py
# Author : Adil
# DateTime : 2019/8/5 4:33 PM
# SoftWare : PyCharm #logintest/api/common/PageHandle.py from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination class MyLimitOffsetPagination(PageNumberPagination):
# 每页显示多少个
page_size = 3
# 默认每页显示3个,可以通过传入pager1/?currentPage=2&pageSize=4,改变默认每页显示的个数
page_size_query_param = "pageSize"
# 最大页数不超过10
max_page_size = 100
# 获取页码数的
page_query_param = "currentPage" # default_limit:表示默认每页显示几条数据
# limit_query_param:表示url中本页需要显示数量参数
# offset_query_param:表示从数据库中的第几条数据开始显示参数
# max_limit:表示每页最大显示数量,做限制使用,避免突然大量的查询数据,数据库崩溃
view 增加分页代码 方式一
# 增加分页 userInfoList = models.User.objects.values().order_by('id') print(userInfoList) page = MyLimitOffsetPagination()
print(page)
page_roles = page.paginate_queryset(queryset=userInfoList, request=request, view=self)
print(page_roles)
roles_ser = PagerSerializer(instance=page_roles, many=True)
print(roles_ser.data)
# return Response(roles_ser.data) # 只返回数据
# return page.get_paginated_response(roles_ser.data) # 返回前后夜url ret = {'code': 1000, 'msg': None, 'data': None,'lens':None}
try:
ret['msg'] = '成功'
ret['data'] = list(page_roles)
print(len(page_roles))
print(len(userInfoList)) ret['lens'] = len(userInfoList) except Exception as e:
ret['code'] = 1001
ret['msg'] = '失败' return (JsonResponse(ret))
这是请求相应如下
方式二
# userlistView.py 创建类
class PagerSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
直接上代码
# FileName : userListView.py
# Author : Adil
# DateTime : 2019/8/2 1:46 PM
# SoftWare : PyCharm from api import models
from django.http import JsonResponse
from rest_framework.views import APIView from api.models import User
from api.utils.auth import Authentication
from api.common.PageHandle import MyLimitOffsetPagination
from rest_framework import serializers class PagerSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__" class userListView(APIView): authentication_classes = [Authentication] # 添加认证
permission_classes = [] # 不尽兴权限控制 def get(self,request,*args,**kwargs): # user1 = models.User.objects.all()
#
# print(user1) # <QuerySet [<User: username: wang,password: 123456>,... # userInfoList = models.User.objects.values() # print('^^^^^')
# for userlist in userInfoList:
#
# # userlist = model_to_dict(userlist)
# print(type(userlist))
# print(userlist) # print(type(userInfoList))
# print("!!!!!")
# userInfoList = model_to_dict(userInfoList)
#
# print(type(userInfoList)) # print(userInfoList) # <QuerySet [{'id': 1, 'username': 'wang', 'password': '123456', 'age': '20', 'e_mail': '272981562@qq.com', 'user_type': 2, 'create_time': datetime.datetime(2019, 7, 30, 21, 16, 12, 301365), 'update_time': datetime.datetime(2019, 7, 30, 21, 16, 12, 301396)}, {'id': 2, ... # for userList in userInfoList:
# #print(userList) # users = models.User.objects.values_list()
# print("8***")
# print(users) # <QuerySet [(1, 'wang', '123456', '20', '272981562@qq.com', 2, datetime.datetime(2019, 7, 30, 21, 16, 12, 301365), datetime.datetime(2019, 7, 30, 21, 16, 12, 301396)), (2, 'yang', '....
# for user in users:
# print(user) # 增加分页 userInfoList = models.User.objects.values().order_by('id') print(userInfoList) page = MyLimitOffsetPagination()
print(page)
page_roles = page.paginate_queryset(queryset=userInfoList, request=request, view=self)
print(page_roles)
roles_ser = PagerSerializer(instance=page_roles, many=True)
print(roles_ser.data)
# return Response(roles_ser.data) # 只返回数据
# return page.get_paginated_response(roles_ser.data) # 返回前后夜url ret = {'code': 1000, 'msg': None, 'data': None,'lens':None}
try:
ret['msg'] = '成功'
ret['data'] = list(page_roles)
print(len(page_roles))
print(len(userInfoList)) ret['lens'] = len(userInfoList) except Exception as e:
ret['code'] = 1001
ret['msg'] = '失败' # return (JsonResponse(ret))
return (page.get_paginated_response(roles_ser.data))
前端
前端预期
添加router
import userlist from '@/components/userlist'
Vue.use(Router) var router = new Router({
routes: [
{
path: '/userlist',
name: 'userlist',
component: userlist
},
新建userlist.vue,里面有两种方式处理后端返回。
<template>
<el-container style="height: 100%; border: 1px solid #eee">
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="['1', '3']">
<el-submenu index="">
<template slot="title"><i class="el-icon-message"></i>导航一</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="1-1">选项1</el-menu-item>
<el-menu-item index="1-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="1-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">选项4</template>
<el-menu-item index="1-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="">
<template slot="title"><i class="el-icon-menu"></i>导航二</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="2-1">选项1</el-menu-item>
<el-menu-item index="2-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="2-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="2-4">
<template slot="title">选项4</template>
<el-menu-item index="2-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="">
<template slot="title"><i class="el-icon-setting"></i>导航三</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="3-1">选项1</el-menu-item>
<el-menu-item index="3-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="3-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="3-4">
<template slot="title">选项4</template>
<el-menu-item index="3-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
</el-menu>
</el-aside> <el-container style="padding-bottom: 15px">
<el-header style="text-align: right; font-size: 12px">
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>退出</el-dropdown-item>
<!-- <el-dropdown-item>新增</el-dropdown-item>
<el-dropdown-item>删除</el-dropdown-item> -->
</el-dropdown-menu>
</el-dropdown>
<span>Adil</span>
</el-header> <el-main>
<el-table :data="tableData">
<el-table-column prop="create_time" label="日期" width="">
</el-table-column>
<el-table-column prop="username" label="姓名" width="">
</el-table-column>
<el-table-column prop="username" label="地址">
</el-table-column>
</el-table>
</el-main>
<el-pagination
background
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 50]"
:page-size="pageSize"
layout=" sizes, prev, pager, next, jumper"
:total="total">
</el-pagination> </el-container>
</el-container> </template> <style>
.el-header {
background-color: #B3C0D1;
color: #333;
line-height: 60px;
} .el-aside {
color: #333;
}
</style> <script>
import axios from 'axios';
export default {
data() {
return {
tableData: [],
total: 0,
currentPage: 1,
pageSize: 10
}
},
created(){
this.getUserList()
},
methods:{
handleSizeChange(size) {
this.pageSize = size;
this.getUserList();
},
handleCurrentChange(current) {
this.currentPage = current;
this.getUserList();
},
getUserList(){
const token = localStorage.getItem('token');
axios.get(`/home/userlist/?token=${token}`,
{headers:{token:localStorage.getItem('token')},
params: {
currentPage: this.currentPage,
pageSize: this.pageSize
}
}).then((res)=>
{
// 后台方式一
// const data = res.data
// this.tableData = data.data;
// this.total = data.lens; // 后台方式二
const data = res.data
this.tableData = data.results;
this.total = data.count; console.log(res.data);
// if (res.data.code===1000){
// // localStorage.setItem('token',res.data.token);
// // this.$router.push({path:'/userlist'});
// }
});
}
} // getUserList(){
// axios.get('/home/userlist/').then((res)=>
// {
// console.log(res);
// // if (res.data.code===1000){
// // // localStorage.setItem('token',res.data.token);
// // // this.$router.push({path:'/userlist'});
// // }
// });
// }
// } }
</script>
方式二的返回结果如下