Django Paginator

Django 分页官方文档  https://docs.djangoproject.com/en/1.10/topics/pagination/

此分页方法没有限制显示出来的页码的个数,会显示全部的页码,待改进。

后端代码

由于代码是先object_list = model_obj.model.objects.all(),然后调用 paginator = Paginator(object_list, 2),如果数据量很大就会消耗很多的性能。

如果是这样呢写呢? paginator = Paginator(model_obj.model.objects.all(), 2)  这样能利用queryset的惰性机制吗? 

看了下Paginator源码,应该是可行的
 class Paginator(object):

     def __init__(self, object_list, per_page, orphans=0,
allow_empty_first_page=True):
self.object_list = object_list
self.per_page = int(per_page)
self.orphans = int(orphans)
self.allow_empty_first_page = allow_empty_first_page def validate_number(self, number):
"""
Validates the given 1-based page number.
"""
try:
number = int(number)
except (TypeError, ValueError):
raise PageNotAnInteger('That page number is not an integer')
if number < 1:
raise EmptyPage('That page number is less than 1')
if number > self.num_pages:
if number == 1 and self.allow_empty_first_page:
pass
else:
raise EmptyPage('That page contains no results')
return number def page(self, number):
"""
Returns a Page object for the given 1-based page number.
"""
number = self.validate_number(number)
bottom = (number - 1) * self.per_page
top = bottom + self.per_page
if top + self.orphans >= self.count:
top = self.count
return self._get_page(self.object_list[bottom:top], number, self) def _get_page(self, *args, **kwargs):
"""
Returns an instance of a single page. This hook can be used by subclasses to use an alternative to the
standard :cls:`Page` object.
"""
return Page(*args, **kwargs) @cached_property
def count(self):
"""
Returns the total number of objects, across all pages.
"""
try:
return self.object_list.count()
except (AttributeError, TypeError):
# AttributeError if object_list has no count() method.
# TypeError if object_list.count() requires arguments
# (i.e. is of type list).
return len(self.object_list) @cached_property
def num_pages(self):
"""
Returns the total number of pages.
"""
if self.count == 0 and not self.allow_empty_first_page:
return 0
hits = max(1, self.count - self.orphans)
return int(ceil(hits / float(self.per_page))) @property
def page_range(self):
"""
Returns a 1-based range of pages for iterating through within
a template for loop.
"""
return six.moves.range(1, self.num_pages + 1) QuerySetPaginator = Paginator # For backwards-compatibility.

Paginator 部分源码


#需要导入 的模块
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def display_table_objs(request,app_name,table_name):
print(app_name,'----',table_name)
#获取数据库数据
model_obj = king_admin.enabled_admins[app_name][table_name] #分页
object_list = model_obj.model.objects.all()
paginator = Paginator(object_list, 2) # Show 2 contacts per page
# paginator = JuncheePaginator(object_list, 1) # Show 2 contacts per page page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages) return render(request,'king_admin/table_objs.html',{"model_obj":model_obj,
"query_sets":contacts,})

前端模板代码

其中的标签样式引用的Bootstrap的样式

 <ul class="pagination">
{# topics.paginator.page_range 这个函数返回包含一个所有页码数的 range 对象 #}
{# 即 range(1, topics.paginator.num_pages + 1) #}
{% if query_sets.has_previous %}
<li><a href="?page={{ query_sets.previous_page_number }}">上一页</a></li>
{% else %}
<li><span>没了</span></li>
{% endif %}
{% for page_number in query_sets.paginator.page_range %} {% ifequal page_number query_sets.number %}
<li class="disabled"><span>{{ page_number }}</span></li> {% else %}
<li ><a href="?page={{ page_number }}">{{ page_number }}</a></li> {% endifequal %}
{% endfor %} {% if query_sets.has_next %}
<li><a href="?page={{ query_sets.next_page_number }}">下一页</a></li>
{% else %}
<li><span>没了</span></li>
{% endif %}
</ul>

效果如下:

Django 之 Paginator 分页功能的更多相关文章

  1. Django——Paginator分页功能练习

    1.路由urls.py from django.contrib import admin from django.urls import path from app01.views import in ...

  2. Django实现简单分页功能

    使用django的第三方模块django-pure-pagination 安装模块: pip install django-pure-pagination 将'pure_pagination'添加到s ...

  3. Django自定制分页功能

    URL: """django_paginner URL Configuration The `urlpatterns` list routes URLs to views ...

  4. 利用rest-framework实现django应用的分页功能

    自定义分页的类,继承 PageNumberPagination class StandardResultsSetPagination(PageNumberPagination): page_size ...

  5. Django 使用Paginator分页

    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger subclass_s = models.subclas ...

  6. 【原】django实现列表分页功能

    在view.py里添加分页查询方法: from django.http import JsonResponse from django.views.decorators.http import req ...

  7. Django,ajax实现表格增删查改,Django内置分页功能。

    1.工程目录 2.urls.py """Django_ajax URL Configuration The `urlpatterns` list routes URLs ...

  8. django内置分页功能扩展

    实现自定制页码数类型class myPaginator(Paginator): def __init__(self,curr_page,per_page_num,*args,**kwargs): se ...

  9. django网页的分页功能,大家如果有疑问请留言

    url文件 from django.contrib import admin from django.conf.urls import url from app01 import views urlp ...

随机推荐

  1. java基础篇3之反射

    1.反射的基础 反射的基石---->Class类 java程序中的各个java类属于同一类事物,描述这类事物的java类名就是Class 获取字节码对应的实例对象(Class类型) class ...

  2. pyhton3 一些排序算法概括

    1.冒泡算法 import random import datetime def maopao(data): # 检测是否排序完成 for i in range(len(data)-1): flag ...

  3. Solidworks拖动装配体的时候物资动力有什么用

    Solidworks物资动力就是模拟真实的场景,你在拖动或旋转零件的时候会和周围的零件碰撞,有相互力的作用. 1 标准拖动   2 碰撞检查   3 选择物资动力(零件上面的黑白相间小圆表示物体重心) ...

  4. jquery 判断元素显示或隐藏

    $().is(":hidden"); $().is(":visible");

  5. Sqlserver 实际开发中表变量的用法

    在实际的开发中,我们可能遇到的问题是,在一个存储过程里面,我们可能要返回多段sql的结果集,但是最终怎么把多个结果集合成一块呢,那么这个时候临时表变量就来了 declare  @tmp table   ...

  6. inflate, findViewById与setContentView的差别与联系

    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentV ...

  7. Kindeditor上传图片回显不出来

    原因之一: 图片成功上传但是回显不出来,这个时候,要检查返回的图片地址是否加了http://这个玩意,不然会将原来的头加上图片返回地址.

  8. T-SQL简单查询语句(模糊查询)

    T-SQL简单查询语句 简单查询: 1.最简单查询(查所有数据) select * from 表名: 注:* 代表所有列 select * from info 2.查询指定列 select code, ...

  9. 【BZOJ3679】数字之积 DFS+DP

    [BZOJ3679]数字之积 Description 一个数x各个数位上的数之积记为f(x) <不含前导零>求[L,R)中满足0<f(x)<=n的数的个数 Input 第一行一 ...

  10. 【BZOJ3291】Alice与能源计划 二分图最大匹配

    [BZOJ3291]Alice与能源计划 Description 在梦境中,Alice来到了火星.不知为何,转眼间Alice被任命为火星能源部长,并立刻面临着一个严峻的考验. 为了方便,我们可以将火星 ...