其他分享
首页 > 其他分享> > Django 数据分页

Django 数据分页

作者:互联网

基于Paginator对象的分页
class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)


Paginator属性
Paginator.count 所有页面的objects总数
Paginator.num_pages 页面总数
Paginator.page_range 页码的范围,从1开始,例如[1, 2, 3, 4]


Paginator方法
Paginator.page(number) 返回一个page对象,number, 当前显示的是第几页



Page对象

class Page(object_list, number, paginator)



Page方法
Page.has_next() 如果有下一页,返回True
Page.has_previous() 如果有上一页,返回 True
Page.has_other_pages() 如果有上一面或下一页,返回True
Page.next_page_number() 返回下一页的页码.如果不存在,抛出InvalidPage异常
Page.previous_page_number() 返回上一页的页码.如果不存在,抛出InvalidPage异常
Page.start_index() 返回当前页上的第一个对象,相对于分页列表的所有对象的序号
Page.end_index() 返回当前页上的最后一个对象,相对于分页列表的所有对象的序号



创建用户小例子
from django.core.paginator import Paginator
class UserViewV2(View):
    def get(self,request,*args,**kwargs):
        queryset = User.objects.all()
        paginator = Paginator(queryset,10)
        try:
            page = int(request.GET.get("page"))
        except:
            page = 1
        if page < 1:
            page = 1
        page = paginator.page(page)
        data = [{"id":user.id,"username":user.username,"email":user.email} for user in page.object_list]
        return JsonResponse(data,safe=False)

    def post(self,request,*args,**kwargs):
        username = request.POST.get("username")
        userpass = request.POST.get("userpass")
        email = request.POST.get('email')
        if not username or userpass or not email:
            return JsonResponse({"errormsg":"参数有误!"})
        user = User.objects.create(username,email,userpass)
        return JsonResponse({"id":user.id,"username":user.username,"email":user.email})
        
        
请求方式

In [1]: import requests                                                                     
In [2]: url = "http://192.168.33.10:8080/dashboard/userview/"                
In [3]: data = {}                                                                                         
In [4]: data["username"] = "zhangsan"                                                     
In [5]: data["userpass"] = '123456'                                                           
In [6]: data["email"] = "zhangsan@alibaba.com"                                     
In [7]: requests.post(url,data)                                                                 
Out[7]: <Response [200]>



 

标签:Paginator,username,分页,page,email,user,Django,数据,Page
来源: https://www.cnblogs.com/l10n/p/14277735.html