django分页查询及对已经分页的数据进行查询,对条件查询后的数据再次分页

#适用于妹子UI的分页前端,其他的也没问题,稍做修改即可
#对已经分页的数据进行查询,对查询后的数据再次进行分页
#思路:url请求除了需要带current page 还需要带查询的内容,以此判断是否查询后的数据分页

直接上代码:

pages:包含两个类1. Pagination表示对全部数据普通分页 2. PaginationQuery表示对条件查询结果进行分页

#适用于妹子UI的分页前端
#适用于所有数据分页,普通分页
class Pagination(object):
    #totalCnt代表表单内容总数量
    def __init__(self,currentPage,perPageCnt,totalCnt,pageIndexCnt,urls):
        self.currentPage = currentPage
        self.perPageCnt = perPageCnt
        self.totalCnt = totalCnt
        self.pageIndexCnt = pageIndexCnt  #表示分页索引显示几个页面,一般显示5个
        self.urls = urls

    #加上@property时,调用方法不用加()
    @property
    def page_nums(self):
        if self.totalCnt%self.perPageCnt == 0:
            return int(self.totalCnt/self.perPageCnt)
        else:
            return int(self.totalCnt/self.perPageCnt)+1
    #其实条数,切片用
    @property
    def startNum(self):
        return (self.currentPage-1)*self.perPageCnt
    @property
    def endNum(self):
        return self.currentPage*self.perPageCnt
    @property
    def prevPage(self):
        return self.currentPage-1
    @property
    def nextPage(self):
        return self.currentPage+1
    #分页显示页码,比如显示: prev<< 4,5,6,7,8 >>next
    @property
    def pageRange(self):
        part = int(self.pageIndexCnt/2)
        if self.pageIndexCnt < self.page_nums:
            if self.currentPage < int(self.pageIndexCnt/2+1):
                return range(1,self.pageIndexCnt+1)
            elif self.currentPage > self.page_nums-part:
                return range(self.page_nums-self.pageIndexCnt,self.page_nums+1)
            else:
                return range(self.currentPage-part,self.currentPage+part+1)
        else:
            return range(1,self.page_nums+1)

    #直接输送代码给模板
    @property
    def pageStr(self):
        pageNumStr = []
        prev_page=""
        next_page=""
        #页码
        if self.currentPage>1 and self.currentPage<self.page_nums:
            prev_page = "<li><a href="+self.urls+"?p=%s>&laquo; Prev</a></li>"%(self.currentPage-1)
            next_page = "<li><a href="+self.urls+"?p=%s>Next &raquo;</a></li>"%(self.currentPage+1)
        if self.currentPage<=1:
            prev_page = "<li class='am-disabled'><a href='#'>&laquo; Prev</a></li>"
        if self.currentPage>=self.page_nums:
            next_page = "<li class='am-disabled'><a href='#'>Next &raquo;</a></li>"

        for page in self.pageRange:
            if page == self.currentPage:
                pageNumStr.append("<li class='am-active'><a href="+self.urls+"?p=%s>%s</a></li>"%(page,page))
            else:
                pageNumStr.append("<li><a href=" + self.urls + "?p=%s>%s</a></li>" % (page, page))
            print(pageNumStr)

        return prev_page+"".join(pageNumStr)+next_page

#适用于妹子UI的分页前端
#对已经分页的数据进行查询,对查询后的数据再次进行分页
#思路:url请求除了需要带current page 还需要带查询的内容
class PaginationQuery(object):
    #content代表需要查询的关键字
    def __init__(self,currentPage,perPageCnt,totalCnt,pageIndexCnt,urls,content):
        self.currentPage = currentPage #当前页码
        self.perPageCnt = perPageCnt #每页要显示多少条
        self.totalCnt = totalCnt  #totalCnt代表表单内容总数量
        self.pageIndexCnt = pageIndexCnt  #表示分页索引显示几个页面,一般显示5个
        self.urls = urls #请求路径
        self.content = content  #查询关键字

    #加上@property时,调用方法不用加()
    @property
    def page_nums(self):
        if self.totalCnt%self.perPageCnt == 0:
            return int(self.totalCnt/self.perPageCnt)
        else:
            return int(self.totalCnt/self.perPageCnt)+1
    #其实条数,切片用
    @property
    def startNum(self):
        return (self.currentPage-1)*self.perPageCnt
    @property
    def endNum(self):
        return self.currentPage*self.perPageCnt
    @property
    def prevPage(self):
        return self.currentPage-1
    @property
    def nextPage(self):
        return self.currentPage+1
    #分页显示页码,比如显示: prev<< 4,5,6,7,8 >>next
    @property
    def pageRange(self):
        part = int(self.pageIndexCnt/2)
        if self.pageIndexCnt < self.page_nums:
            if self.currentPage < int(self.pageIndexCnt/2+1):
                return range(1,self.pageIndexCnt+1)
            elif self.currentPage > self.page_nums-part:
                return range(self.page_nums-self.pageIndexCnt,self.page_nums+1)
            else:
                return range(self.currentPage-part,self.currentPage+part+1)
        else:
            return range(1,self.page_nums+1)

    #直接输送代码给模板
    @property
    def pageStr(self):
        pageNumStr = []
        prev_page=""
        next_page=""
        #页码
        if self.currentPage>1 and self.currentPage<self.page_nums:
            prev_page = "<li><a href="+self.urls+"?p=%s&content=%s>&laquo; Prev</a></li>"%(self.currentPage-1,self.content)
            next_page = "<li><a href="+self.urls+"?p=%s&content=%s>Next &raquo;</a></li>"%(self.currentPage+1,self.content)
        if self.currentPage<=1:
            prev_page = "<li class='am-disabled'><a href='#'>&laquo; Prev</a></li>"
        if self.currentPage>=self.page_nums:
            next_page = "<li class='am-disabled'><a href='#'>Next &raquo;</a></li>"

        for page in self.pageRange:
            if page == self.currentPage:
                pageNumStr.append("<li class='am-active'><a href="+self.urls+"?p=%s&content=%s>%s</a></li>"%(page,self.content,page))
            else:
                pageNumStr.append("<li><a href=" + self.urls + "?p=%s&content=%s>%s</a></li>"%(page,self.content,page))
            # print(pageNumStr)

        return prev_page+"".join(pageNumStr)+next_page

分页数据views: 

1 issueIndex  因为获取的是所有值,进行普通分页,调用Pagination

2 seleIssue 因为进行了条件查询,所以对条件查询后的内容进行分页,调用PaginationQuery类

因为做项目,其他多余代码请略过:

from django.shortcuts import render,HttpResponse,redirect
from app1 import models
from django import forms
from django.db.models import F,Q
from app1.views.pages import Pagination,PaginationQuery

def issueIndex(request):
    issues = models.IssueList.objects.all().order_by("-issueDate")
    #分页
    currentPage = int(request.GET.get("p",1)) #当前页,如果没有默认1
    perPageCnt = 10 #每页显示10个数据
    totalCnt = models.IssueList.objects.all().count() #获取全部数据个数
    pageIndexCnt = 5  #显示页码 5个,
    print(currentPage, "currentpage",totalCnt,pageIndexCnt,request.path)
    pagination = Pagination(currentPage,perPageCnt,totalCnt,pageIndexCnt,request.path)
    if currentPage > 0 and currentPage< pagination.page_nums:
        issues = issues[pagination.startNum:pagination.endNum]
    elif currentPage == pagination.page_nums:
        issues = issues[pagination.startNum::]
    else:
        issues = issues[0:10]
    return render(request,"issueIndex.html",{"issues":issues,"pagination":pagination})


def seleIssue(request):
    content = request.GET.get("content", None)
    #判断是否有查询内容
    if content:
        issues = models.IssueList.objects.filter(Q(cusCompanyForIssue__companyName__icontains=content) |
                                                 Q(issueType__name__icontains=content) |
                                                 Q(issueContent__icontains=content) |
                                                 Q(status__icontains=content) |
                                                 Q(issueDept__dept__icontains=content)).order_by("-issueDate")
    else:
        issues = models.IssueList.objects.all().order_by("-issueDate")
    #分页显示
    currentPage = int(request.GET.get("p", 1))  # 当前页,如果没有默认1
    perPageCnt = 10  # 每页显示10个数据
    totalCnt = issues.count()  # 获取全部数据个数
    pageIndexCnt = 5  # 显示页码 5个,
    print(currentPage, "currentpage", totalCnt, pageIndexCnt, request.path)
    #判断是否有查询,如果没有就取全部index即可(调用PaginationQuery),如果有内容就调用PaginationQuery
    if content:
        pagination = PaginationQuery(currentPage, perPageCnt, totalCnt, pageIndexCnt, request.path,content)
    else:
        pagination = Pagination(currentPage, perPageCnt, totalCnt, pageIndexCnt, request.path)
    #获取当前页面要显示的内容,使用切片模式
    if currentPage > 0 and currentPage < pagination.page_nums:
        issues = issues[pagination.startNum:pagination.endNum]
    elif currentPage == pagination.page_nums:
        issues = issues[pagination.startNum::]
    else:
        issues = issues[0:10]

    return render(request, "issueIndex.html", {"issues": issues,"pagination":pagination})

def delIssue(request):
    cid = request.GET.get("cid",None)
    models.IssueList.objects.filter(id=cid).delete()
    return redirect("/issueIndex.html/")

class addIssueForm(forms.Form):
    # 缺失时间
    issueDate = forms.DateField()
    # 稽核人员
    auditPerson = forms.CharField(max_length=128,required=False)
    # 缺失内容
    issueContent = forms.CharField(max_length=256,required=False)
    # 改善对策
    improve = forms.CharField(max_length=512,required=False)
    # 缺失状态
    status = forms.CharField(max_length=16,required=False)
    # 备注
    mark = forms.CharField(max_length=256,required=False)
    # Status(隐藏)
    # hide = forms.BooleanField()

def editIssue(request):
    if request.method=="GET":
        issueId = request.GET.get("cid",None)
        qses = models.QSMember.objects.all()
        issuedepts = models.IssueDept.objects.all()
        issueTypes = models.IssueType.objects.all()
        issue = models.IssueList.objects.filter(id=issueId).first()
        companys = models.CustomerInfo.objects.all()
        print(issue.cusCompanyForIssue.id)
        print(issue.hide)
        #locals()传递所有参数
        return render(request,"editIssue.html",locals())
    else:
        obj = addIssueForm(request.POST)
        cid = request.GET.get("cid",None)
        print(cid)
        companyId = request.POST.get("cusComanpyForIssue", None)
        issueType = request.POST.get("issueType", None)
        issueDept = request.POST.get("issueDept", None)
        qs = request.POST.get("issueListQS", None)
        hide = request.POST.get("hide", None)
        file = request.FILES.get("files")
        issueSite = request.POST.get("issueSite", None)
        issue = models.IssueList.objects.filter(id=cid)
        if obj.is_valid():
            issue.update(**obj.cleaned_data,issueType_id=issueType,cusCompanyForIssue_id=companyId,issueSite=issueSite,
                                                        issueDept_id=issueDept,issueListQS_id=qs,hide=hide)
            if file:
                #清除files 第一种写法
                models.UploadFile.objects.filter(issueFiles=cid).delete()
                import uuid, os
                from ctcqs import settings
                # 因为一直报错FileNotFound,所以只能先这样写,真的是醉了,搞了好几个小时了# 绝对路径
                filepath1 = os.path.join("issueList", str(uuid.uuid4()) + file.name)
                # 相对路径 for以后使用
                filepath = os.path.join(settings.MEDIA_ROOT, filepath1)
                # 创建file
                file_obj = models.UploadFile.objects.create(name=file.name, path=filepath1, size=file.size)
                # 因为一直路径报错,所以这里准备改,结果成功了,算了
                newfile = open(filepath, "wb")
                for item in file.chunks():
                    newfile.write(item)
                newfile.close()
                issue.first().files.add(file_obj)
            return redirect("/issueIndex.html/")


def addIssue(request):
    if request.method=="GET":
        companys = models.CustomerInfo.objects.all()
        qses = models.QSMember.objects.all()
        issuedepts = models.IssueDept.objects.all()
        issueTypes = models.IssueType.objects.all()
        return render(request,"addIssue.html",{"companys":companys,"qses":qses,"issuedepts":issuedepts,"issueTypes":issueTypes})
    else:
        obj = addIssueForm(request.POST)
        companyId = request.POST.get("cusComanpyForIssue",None)
        issueType = request.POST.get("issueType",None)
        issueDept = request.POST.get("issueDept",None)
        qs = request.POST.get("issueListQS",None)
        hide = request.POST.get("hide",None)
        issueSite = request.POST.get("issueSite", None)
        file = request.FILES.get("files")
        # print(obj)
        if obj.is_valid():
            #新增issuelist Item
            print("是否隐藏", hide)
            issue = models.IssueList.objects.create(**obj.cleaned_data,issueType_id=issueType,cusCompanyForIssue_id=companyId,
                                                    issueDept_id=issueDept,issueListQS_id=qs,hide=hide,issueSite=issueSite)
            #如果file不为空
            if file:
                import uuid,os
                from ctcqs import settings
                # 因为一直报错FileNotFound,所以只能先这样写,真的是醉了,搞了好几个小时了# 绝对路径
                filepath1 = os.path.join("issueList", str(uuid.uuid4()) + file.name)
                # 相对路径 for以后使用
                filepath = os.path.join(settings.MEDIA_ROOT, filepath1)
                # 创建file
                file_obj = models.UploadFile.objects.create(name=file.name, path=filepath1, size=file.size)
                # 因为一直路径报错,所以这里准备改,结果成功了,算了
                newfile = open(filepath, "wb")
                for item in file.chunks():
                    newfile.write(item)
                newfile.close()
                issue.files.add(file_obj)
        return redirect("/issueIndex.html/")

前端纯分页HTML页面,那个页面需要的时候只需要引用进来即可

引用方式: 

{% include "include/pageindexIssue.html" %}

分页HTML内容:pageindexIssue.html,因为我做了首页、尾页、跳转等,

实际上只要一句话即可做到完全分页:

{{ pagination.pageStr|safe }}
<ul class="am-pagination am-pagination-centered">
    <li>共{{ pagination.totalCnt }}条数据&nbsp</li>
    <li><a href="{{ pagination.urls }}?p=1">首页</a></li>

    {{ pagination.pageStr|safe }}

    <li><a href="{{ pagination.urls }}?p={{ pagination.page_nums }}">尾页</a></li>
    <li>
         总页数: {{ pagination.page_nums }}
    </li>
    <li>&nbsp;
    <input type="text" name="pageNum" id="pageNum" style="width: 60px">
    <button type="button" class="am-btn am-btn-default  am-btn-sm" onclick="fun()">跳转页</button>
    </li>
</ul>

<script>
    function fun() {
        var pageNum = document.getElementById('pageNum').value;
        window.location.href= '{{ pagination.urls }}?p='+pageNum;
    }
</script>

分页效果:

1 全部数据分页:

2 条件查询后内容分页效果:

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值