后端
配置urls
# 导入vIEwfrom 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 : PyCharmfrom API import modelsfrom django.http import JsonResponsefrom rest_framework.vIEws import APIVIEwfrom API.models import Userfrom API.utils.auth import Authenticationfrom API.common.PageHandle import MylimitOffsetPaginationfrom rest_framework import serializersclass 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‘: ‘[email protected]‘,‘user_type‘: 2,‘create_time‘: datetime.datetime(2019,7,30,21,16,12,301365),‘update_time‘: datetime.datetime(2019,301396)},{‘ID‘: 2,... # for userList in userInfoList: # #print(userList) # users = models.User.objects.values_List() # print("8***") # print(users) # <querySet [(1,‘wang‘,‘123456‘,‘20‘,‘[email protected]‘,2,datetime.datetime(2019,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.pyfrom rest_framework.pagination import limitOffsetPagination,PageNumberPaginationclass 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,‘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 : PyCharmfrom API import modelsfrom django.http import JsonResponsefrom rest_framework.vIEws import APIVIEwfrom API.models import Userfrom API.utils.auth import Authenticationfrom API.common.PageHandle import MylimitOffsetPaginationfrom rest_framework import serializersclass PagerSerializer(serializers.ModelSerializer): class Meta: model = User fIElds = "__all__"class userListVIEw(APIVIEw): authentication_classes = [Authentication] # 添加认证 permission_classes = [] # 不尽兴权限控制 def get(self,‘e_mail‘: ‘[email protected]‘,‘[email protected]‘,‘.... # 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,‘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="1"> <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="2"> <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="3"> <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="140"> </el-table-column> <el-table-column prop="username" label="姓名" wIDth="120"> </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,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>
方式二的返回结果如下
总结以上是内存溢出为你收集整理的django rest_framework vue 实现用户列表分页全部内容,希望文章能够帮你解决django rest_framework vue 实现用户列表分页所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)