django rest_framework vue 实现用户列表分页

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)  # ,...




        # 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)   #  

        # for userList in userInfoList:
        #     #print(userList)

        # users = models.User.objects.values_list()
        # print("8***")
        # print(users)  # 
        # 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。

查看接口返回

django rest_framework vue 实现用户列表分页_第1张图片

 

可以看到此时返回的是查询所有结果,有21条数据。

 django rest_framework vue 实现用户列表分页_第2张图片

 

可以看到 这样返回的结果是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))

 

这是请求相应如下

django rest_framework vue 实现用户列表分页_第3张图片

 

 

方式二

# 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)  # ,...




        # 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)   #  

        # for userList in userInfoList:
        #     #print(userList)

        # users = models.User.objects.values_list()
        # print("8***")
        # print(users)  # 
        # 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))

 

 

 

前端

前端预期

django rest_framework vue 实现用户列表分页_第4张图片

 

 添加router

 

import userlist from '@/components/userlist'
Vue.use(Router)

var router =  new Router({
  routes: [
    {
      path: '/userlist',
      name: 'userlist',
      component: userlist
    },

 

新建userlist.vue,里面有两种方式处理后端返回。

 






方式二的返回结果如下

django rest_framework vue 实现用户列表分页_第5张图片

 

转载于:https://www.cnblogs.com/BlueSkyyj/p/11307904.html

你可能感兴趣的:(django rest_framework vue 实现用户列表分页)