一、Django的內置分頁器(paginator) view index.html: 擴展 show.html model.py文件內容: 二、自定義分頁 當資料庫中數據有很多,我們通常會在前端頁面做分頁展示。 分頁的數據可以在前端頁面實現,也可以在後端實現分頁。 後端實現分頁的原理就是每次只請求一 ...
一、Django的內置分頁器(paginator)
view
from django.shortcuts import render,HttpResponse
# Create your views here.
from app01.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
'''
批量導入數據:
Booklist=[]
for i in range(100):
Booklist.append(Book(title="book"+str(i),price=30+i*i))
Book.objects.bulk_create(Booklist)
'''
'''
分頁器的使用:
book_list=Book.objects.all()
paginator = Paginator(book_list, 10)
print("count:",paginator.count) #數據總數
print("num_pages",paginator.num_pages) #總頁數
print("page_range",paginator.page_range) #頁碼的列表
page1=paginator.page(1) #第1頁的page對象
for i in page1: #遍歷第1頁的所有數據對象
print(i)
print(page1.object_list) #第1頁的所有數據
page2=paginator.page(2)
print(page2.has_next()) #是否有下一頁
print(page2.next_page_number()) #下一頁的頁碼
print(page2.has_previous()) #是否有上一頁
print(page2.previous_page_number()) #上一頁的頁碼
# 拋錯
#page=paginator.page(12) # error:EmptyPage 超過頁碼範圍
#page=paginator.page("z") # error:PageNotAnInteger 非法頁碼值
#page = page_obj.page(-1) #That page number is less than 1 ,也是EmptyPage的錯誤,頁碼不能為負數,最少也是1
'''
book_list=Book.objects.all()
paginator = Paginator(book_list, 10) #按照每頁顯示10條來計算
page = request.GET.get('page',1) #將來訪問的url是這樣的 http://127.0.0.1:8000/路徑/?page=1
currentPage=int(page)
try:
print(page)
book_list = paginator.page(page)
except PageNotAnInteger:
book_list = paginator.page(1)
except EmptyPage:
book_list = paginator.page(paginator.num_pages)
return render(request,"index.html",{"book_list":book_list,"paginator":paginator,"currentPage":currentPage})
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h4>分頁器</h4>
<ul>
{% for book in book_list %}
<li>{{ book.title }} -----{{ book.price }}</li>
{% endfor %}
</ul>
<ul class="pagination" id="pager">
{% if book_list.has_previous %}
<li class="previous"><a href="/index/?page={{ book_list.previous_page_number }}">上一頁</a></li>
{% else %}
<li class="previous disabled"><a href="#">上一頁</a></li>
{% endif %}
{% for num in paginator.page_range %}
{% if num == currentPage %}
<li class="item active"><a href="/index/?page={{ num }}">{{ num }}</a></li>
{% else %}
<li class="item"><a href="/index/?page={{ num }}">{{ num }}</a></li>
{% endif %}
{% endfor %}
{% if book_list.has_next %}
<li class="next"><a href="/index/?page={{ book_list.next_page_number }}">下一頁</a></li>
{% else %}
<li class="next disabled"><a href="#">下一頁</a></li>
{% endif %}
</ul>
</div>
</body>
</html>
擴展
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def show(request):
book_objs = models.Book.objects.all()
page_obj = Paginator(book_objs,1)
print('數據總數',page_obj.count)
print('總頁數',page_obj.num_pages)
print('頁碼列表',page_obj.page_range)
page1 = page_obj.page(1)
for i in page1:
print(i)
print(page1.object_list)
page2 = page_obj.page(2)
print(page2.has_previous())
print(page2.has_next())
print(page2.next_page_number())
print(page2.previous_page_number())
# page = page_obj.page(-1)
page_num = request.GET.get('page',1)
try:
current_page_num = int(page_num)
page_num_data = page_obj.page(current_page_num)
except PageNotAnInteger:
current_page_num = 1
page_num_data = page_obj.page(current_page_num)
except EmptyPage:
current_page_num = page_obj.num_pages
page_num_data = page_obj.page(current_page_num)
except Exception:
current_page_num = 1
page_num_data = page_obj.page(current_page_num)
if page_obj.num_pages > 11: #擴展,如果總的頁碼數大於了11,我們就不把所有的頁碼數顯示出來了,只顯示其中11個頁面,當前頁左邊5個,右邊5個
if current_page_num - 5 < 1:
pageRange = range(1,12)
elif current_page_num + 5 > page_obj.num_pages:
pageRange = range(page_obj.num_pages-10,page_obj.num_pages+1)
else:
pageRange = range(current_page_num - 5,current_page_num + 6)
else:
pageRange = page_obj.page_range
book_objs = page_num_data
return render(request,'show.html',{'book_objs':book_objs,'current_page_num':current_page_num,'page_obj':page_obj,'pageRange':pageRange})
show.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'bootstrap-3.3.0-dist/dist/css/bootstrap.min.css' %}">
</head>
<body>
<h1>數據展示</h1>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>價格</th>
<th>性別</th>
<th>出版日期</th>
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book_obj in book_objs %}
<tr>
<td>{{ book_obj.pk }}</td>
<td>{{ book_obj.title }}</td>
<td>{{ book_obj.price }}</td>
<td>{{ book_obj.get_sex_display }}</td>
<td>{{ book_obj.publishDate|date:'Y-d-m' }}</td>
<td>{{ book_obj.publish.name }}</td>
<td>
{% for author in book_obj.authors.all %}
{{ author.name }}
{% endfor %}
</td>
<td>
<a class="btn btn-warning" href="{% url 'edit_book' book_obj.pk %}">編輯</a>
<a class="btn btn-danger" href="{% url 'delete_book' book_obj.pk %}">刪除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul class="pagination" id="pager">
{% if book_objs.has_previous %}
<li class="previous"><a href="/show/?page={{ book_objs.previous_page_number }}">上一頁</a></li>
{% else %}
<li class="previous disabled"><a href="javascript:void(0)">上一頁</a></li>
{% endif %}
<!--{% for num in page_obj.page_range %}-->
{% for num in pageRange %}
{% if num == current_page_num %}
<li class="item active"><a href="/show/?page={{ num }}">{{ num }}</a></li>
{% else %}
<li class="item"><a href="/show/?page={{ num }}">{{ num }}</a></li>
{% endif %}
{% endfor %}
{% if book_objs.has_next %}
<li class="next"><a href="/show/?page={{ book_objs.next_page_number }}">下一頁</a></li>
{% else %}
<li class="next disabled"><a href="#">下一頁</a></li>
{% endif %}
</ul>
</div>
</div>
</div>
</body>
<script src="{% static 'bootstrap-3.3.0-dist/dist/jQuery/jquery-3.1.1.js' %}"></script>
<script src="{% static 'bootstrap-3.3.0-dist/dist/js/bootstrap.min.js' %}"></script>
</html>
model.py文件內容:
from django.db import models
# Create your models here.
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField( max_length=32)
age=models.IntegerField()
authorDetail=models.OneToOneField(to="AuthorDetail",to_field="nid")
def __str__(self):
return self.name
class AuthorDetail(models.Model):
nid = models.AutoField(primary_key=True)
birthday=models.DateField()
telephone=models.BigIntegerField()
addr=models.CharField( max_length=64)
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField( max_length=32)
city=models.CharField( max_length=32)
email=models.EmailField()
def __str__(self):
return self.name
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField( max_length=32)
publishDate=models.DateField()
price=models.DecimalField(max_digits=5,decimal_places=2)
publish=models.ForeignKey(to="Publish",to_field="nid")
authors=models.ManyToManyField(to='Author',)
def __str__(self):
return self.title
二、自定義分頁
當資料庫中數據有很多,我們通常會在前端頁面做分頁展示。
分頁的數據可以在前端頁面實現,也可以在後端實現分頁。
後端實現分頁的原理就是每次只請求一頁數據。
準備工作
我們使用腳本批量創建一些測試數據(將下麵的代碼保存到bulk_create.py文件中放到Django項目的根目錄,直接執行即可。):
import os
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "about_orm.settings")
import django
django.setup()
from app01 import models
bulk_obj = (models.Publisher(name='第{}出版社'.format(i)) for i in range(300))
models.Publisher.objects.bulk_create(bulk_obj) #批量添加,註意寫法
看下麵幾個版本的分頁:
def publisher_list(request):
# 從URL中取當前訪問的頁碼數
try:
current_page = int(request.GET.get('page'))
except Exception as e:
# 取不到或者頁碼數不是數字都預設展示第1頁
current_page = 1
# 總數據量
total_count = models.Publisher.objects.count()
# 定義每頁顯示多少條數據
per_page = 10
# 計算出總頁碼數
total_page, more = divmod(total_count, per_page)
if more:
total_page += 1
# 定義頁面上最多顯示多少頁碼(為了左右對稱,一般設為奇數)
max_show = 11
half_show = max_show // 2
# 計算一下頁面顯示的頁碼範圍
if total_page <= max_show: # 總頁碼數小於最大顯示頁碼數
page_start = 1
page_end = total_page
elif current_page + half_show >= total_page: # 右邊越界
page_end = total_page
page_start = total_page - max_show
elif current_page - half_show <= 1: # 左邊越界
page_start = 1
page_end = max_show
else: # 正常頁碼區間
page_start = current_page - half_show
page_end = current_page + half_show
# 數據索引起始位置
data_start = (current_page-1) * per_page
data_end = current_page * per_page
publisher_list = models.Publisher.objects.all()[data_start:data_end]
# 生成頁面上顯示的頁碼
page_html_list = []
page_html_list.append('<nav aria-label="Page navigation"><ul class="pagination">')
# 加首頁
first_li = '<li><a href="/publisher_list/?page=1">首頁</a></li>'
page_html_list.append(first_li)
# 加上一頁
if current_page == 1:
prev_li = '<li><a href="#"><span aria-hidden="true">«</span></a></li>'
else:
prev_li = '<li><a href="/publisher_list/?page={}"><span aria-hidden="true">«</span></a></li>'.format(current_page - 1)
page_html_list.append(prev_li)
for i in range(page_start, page_end + 1):
if i == current_page:
li_tag = '<li class="active"><a href="/publisher_list/?page={0}">{0}</a></li>'.format(i)
else:
li_tag = '<li><a href="/publisher_list/?page={0}">{0}</a></li>'.format(i)
page_html_list.append(li_tag)
# 加下一頁
if current_page == total_page:
next_li = '<li><a href="#"><span aria-hidden="true">»</span></a></li>'
else:
next_li = '<li><a href="/publisher_list/?page={}"><span aria-hidden="true">»</span></a></li>'.format(current_page + 1)
page_html_list.append(next_li)
# 加尾頁
page_end_li = '<li><a href="/publisher_list/?page={}">尾頁</a></li>'.format(total_page)
page_html_list.append(page_end_li)
page_html_list.append('</ul></nav>')
page_html = "".join(page_html_list)
return render(request, "publisher_list.html", {"publisher_list": publisher_list, "page_html": page_html})
class Pagination(object):
"""自定義分頁(Bootstrap版)"""
def __init__(self, current_page, total_count, base_url, per_page=10, max_show=11):
"""
:param current_page: 當前請求的頁碼
:param total_count: 總數據量
:param base_url: 請求的URL
:param per_page: 每頁顯示的數據量,預設值為10
:param max_show: 頁面上最多顯示多少個頁碼,預設值為11
"""
try:
self.current_page = int(current_page)
except Exception as e:
# 取不到或者頁碼數不是數字都預設展示第1頁
self.current_page = 1
# 定義每頁顯示多少條數據
self.per_page = per_page
# 計算出總頁碼數
total_page, more = divmod(total_count, per_page)
if more:
total_page += 1
self.total_page = total_page
# 定義頁面上最多顯示多少頁碼(為了左右對稱,一般設為奇數)
self.max_show = max_show
self.half_show = max_show // 2
self.base_url = base_url
@property
def start(self):
return (self.current_page-1) * self.per_page
@property
def end(self):
return self.current_page * self.per_page
def page_html(self):
# 計算一下頁面顯示的頁碼範圍
if self.total_page <= self.max_show: # 總頁碼數小於最大顯示頁碼數
page_start = 1
page_end = self.total_page
elif self.current_page + self.half_show >= self.total_page: # 右邊越界
page_end = self.total_page
page_start = self.total_page - self.max_show
elif self.current_page - self.half_show <= 1: # 左邊越界
page_start = 1
page_end = self.max_show
else: # 正常頁碼區間
page_start = self.current_page - self.half_show
page_end = self.current_page + self.half_show
# 生成頁面上顯示的頁碼
page_html_list = []
page_html_list.append('<nav aria-label="Page navigation"><ul class="pagination">')
# 加首頁
first_li = '<li><a href="{}?page=1">首頁</a></li>'.format(self.base_url)
page_html_list.append(first_li)
# 加上一頁
if self.current_page == 1:
prev_li = '<li><a href="#"><span aria-hidden="true">«</span></a></li>'
else:
prev_li = '<li><a href="{}?page={}"><span aria-hidden="true">«</span></a></li>'.format(
self.base_url, self.current_page - 1)
page_html_list.append(prev_li)
for i in range(page_start, page_end + 1):
if i == self.current_page:
li_tag = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(self.base_url, i)
else:
li_tag = '<li><a href="{0}?page={1}">{1}</a></li>'.format(self.base_url, i)
page_html_list.append(li_tag)
# 加下一頁
if self.current_page == self.total_page:
next_li = '<li><a href="#"><span aria-hidden="true">»</span></a></li>'
else:
next_li = '<li><a href="{}?page={}"><span aria-hidden="true">»</span></a></li>'.format(
self.base_url, self.current_page + 1)
page_html_list.append(next_li)
# 加尾頁
page_end_li = '<li><a href="{}?page={}">尾頁</a></li>'.format(self.base_url, self.total_page)
page_html_list.append(page_end_li)
page_html_list.append('</ul></nav>')
return "".join(page_html_list)
def publisher_list(request):
# 從URL中取當前訪問的頁碼數
current_page = int(request.GET.get('page'))
# 比len(models.Publisher.objects.all())更高效
total_count = models.Publisher.objects.count()
page_obj = Pagination(current_page, total_count, request.path_info)
data = models.Publisher.objects.all()[page_obj.start:page_obj.end]
page_html = page_obj.page_html()
return render(request, "publisher_list.html", {"publisher_list": data, "page_html": page_html})
再來一版django內置分頁器的分頁
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
L = []
for i in range(999):
L.append(i)
def index(request):
current_page = request.GET.get('p')
paginator = Paginator(L, 10)
# per_page: 每頁顯示條目數量
# count: 數據總個數
# num_pages:總頁數
# page_range:總頁數的索引範圍,如: (1,10),(1,200)
# page: page對象
try:
posts = paginator.page(current_page)
# has_next 是否有下一頁
# next_page_number 下一頁頁碼
# has_previous 是否有上一頁
# previous_page_number 上一頁頁碼
# object_list 分頁之後的數據列表
# number 當前頁
# paginator paginator對象
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request, 'index.html', {'posts': posts})
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
{% for item in posts %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<div class="pagination">
<span class="step-links">
{% if posts.has_previous %}
<a href="?p={{ posts.previous_page_number }}">Previous</a>
{% endif %}
<span class="current">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
</span>
{% if posts.has_next %}
<a href="?p={{ posts.next_page_number }}">Next</a>
{% endif %}
</span>
</div>
</body>
</html>