自定義分頁器的使用,創建一個用來存儲外來的組件(utils), 建一個py文件將代碼直接拷貝過去css
# @Author :SkyOcean # @Time:2019/10/2914:06 # @File :mypage.py class Pagination(object): def __init__(self, current_page, all_count, per_page_num=5, pager_count=11): """ 封裝分頁相關數據 :param current_page: 當前頁:current_page = request.GET.get('page',1) :param all_count: 數據庫中的數據總條數 :param per_page_num: 每頁顯示的數據條數 :param pager_count: 最多顯示的頁碼個數 用法: queryset = model.objects.all() page_obj = Pagination(current_page,all_count) page_data = queryset[page_obj.start:page_obj.end] 獲取數據用page_data而再也不使用原始的queryset 獲取前端分頁樣式用page_obj.page_html """ try: current_page = int(current_page) except Exception as e: current_page = 1 if current_page < 1: current_page = 1 self.current_page = current_page self.all_count = all_count self.per_page_num = per_page_num # 總頁碼 all_pager, tmp = divmod(all_count, per_page_num) if tmp: all_pager += 1 self.all_pager = all_pager self.pager_count = pager_count self.pager_count_half = int((pager_count - 1) / 2) @property def start(self): return (self.current_page - 1) * self.per_page_num @property def end(self): return self.current_page * self.per_page_num def page_html(self): # 若是總頁碼 < 11個: if self.all_pager <= self.pager_count: pager_start = 1 pager_end = self.all_pager + 1 # 總頁碼 > 11 else: # 當前頁若是<=頁面上最多顯示11/2個頁碼 if self.current_page <= self.pager_count_half: pager_start = 1 pager_end = self.pager_count + 1 # 當前頁大於5 else: # 頁碼翻到最後 if (self.current_page + self.pager_count_half) > self.all_pager: pager_end = self.all_pager + 1 pager_start = self.all_pager - self.pager_count + 1 else: pager_start = self.current_page - self.pager_count_half pager_end = self.current_page + self.pager_count_half + 1 page_html_list = [] # 添加前面的nav和ul標籤 page_html_list.append(''' <nav aria-label='Page navigation>' <ul class='pagination'> ''') first_page = '<li><a href="?page=%s">首頁</a></li>' % (1) page_html_list.append(first_page) if self.current_page <= 1: prev_page = '<li class="disabled"><a href="#">上一頁</a></li>' else: prev_page = '<li><a href="?page=%s">上一頁</a></li>' % (self.current_page - 1,) page_html_list.append(prev_page) for i in range(pager_start, pager_end): if i == self.current_page: temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,) else: temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,) page_html_list.append(temp) if self.current_page >= self.all_pager: next_page = '<li class="disabled"><a href="#">下一頁</a></li>' else: next_page = '<li><a href="?page=%s">下一頁</a></li>' % (self.current_page + 1,) page_html_list.append(next_page) last_page = '<li><a href="?page=%s">尾頁</a></li>' % (self.all_pager,) page_html_list.append(last_page) # 尾部添加標籤 page_html_list.append(''' </nav> </ul> ''') return ''.join(page_html_list)
from app01.utils.mypage import Pagination 使用封裝好的分頁器代 def login(request): book_queryset = models.Book.objects.all() current_page = request.GET.get('page',1) all_count = book_queryset.count() 1.實例化產生對象 page_obj = Pagination(current_page=current_page,all_count=all_count) 2.對真實數據進行切片操做 page_queryset = book_queryset[page_obj.start:page_obj.end] return render(request,'login.html',locals())
{% for book_obj in page_queryset %} <p>{{ book_obj.title }}</p> {% endfor %} {{ page_obj.page_html|safe }}
views後端html
def index(request): # 1.獲取用戶想要訪問的頁碼數 current_page = request.GET.get('page',1) # 若是沒有page參數 默認就展現第一頁 # 轉成整型 current_page = int(current_page) # 2.每頁展現10條數據 per_page_num = 10 # 3.定義起始位置和終止位置 start_page = (current_page - 1) * per_page_num end_page = current_page * per_page_num # 4.統計數據的總條數 book_queryset = models.Book.objects.all() all_count = book_queryset.count() # 5.求數據到底須要多少頁才能展現完 page_num, more = divmod(all_count,per_page_num) # divmod(100,10) if more: page_num += 1 # page_num就以爲了 須要多少個頁碼 page_html = '' xxx = current_page # xxx就是用戶點擊的數字 if current_page < 6: current_page = 6 for i in range(current_page-5,current_page+6): if xxx == i: page_html += '<li class="active"><a href="?page=%s">%s</a></li>'%(i,i) else: page_html += '<li><a href="?page=%s">%s</a></li>' % (i, i) book_queryset = book_queryset[start_page:end_page] return render(request,'index.html',locals())
html前端前端
<table class="table table-hover table-bordered"> <thead> <tr> <th>id</th> <th>書名</th> <th>詳情</th> <th>操做</th> </tr> </thead> <tbody> {% for page in book_querset %} <tr> <td>{{ forloop.counter }}</td> <td>{{ page.title }}</td> <td>{{ page.addr }}</td> <td> <a href="">添加</a> <a href="">刪除</a> </td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {{ page_html|safe }} <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav>
from django.db import models # Create your models here. class Test(models.Model): name = models.CharField(max_length=32, null=True, default=None) age = models.IntegerField(max_length=32, null=True, default=None)
urlpatterns = [ path('admin/', admin.site.urls), path("favicon.ico", RedirectView.as_view(url='static/favicon.ico')), re_path('^index/',views.index), ]
def index(request): product_list_to_insert = list() for i in range(1000): product_list_to_insert.append(models.Test(name='123')) models.Test.objects.bulk_create(product_list_to_insert)
# ############### 添加數據 ############### def index(request): import random product_list_to_insert = list() for x in range(100): #注意下面的添加方式 product_list_to_insert.append(models.Test(name='apollo' + str(x), age=random.randint(18, 89))) models.Test.objects.bulk_create(product_list_to_insert) return render(request, 'index.html')
批量更新數據時,先進行數據過濾,而後再調用update方法進行一次性地更新。下面的語句將生成相似update....frrom....的SQL語句。 # ############### 更新數據 ############### Test.objects.filter(name__contains='apollo1').update(name='Jack')
批量更新數據時,先是進行數據過濾,而後再調用delete方法進行一次性刪除。 下面的語句講生成相似delete from ... where ... 的SQL語句。 # ############### 刪除數據 ############### Test.objects.filter(name__contains='jack').delete()
優勢:好處在於 django orm會自動幫你建立第三張關係表
缺點:可是它只會幫你建立兩個表的關係字段(倆個book_id,author_id) 不會再額外添加字段
雖然方便 可是第三張表的擴展性較差 沒法隨意的添加額外的字段python
class Book(models.Model): ... authors = models.ManyToManyField(to='Author') class Author(models.Models): ...
本身手動添加外鍵數據庫
優勢:好處在於第三張表是能夠任意的添加額外的字段django
缺點:不足之處是在於orm查詢的時候,不少方法不支持,查詢的時候很是的麻煩bootstrap
class Book(models.Model): ... class Author(models.Models): ... class Book2Author(models.Model): book_id = models.ForeignKey(to='Book') author_id = models.ForeignKey(to='Author') create_time = models.DateField(auto_now_add=True)
3.半自動(推薦使用******)
手動建表 可是你會告訴orm 第三張表是你本身建的
orm只須要給我提供方便的查詢方法
第三種雖然可使用orm查詢方法,可是不支持使用下面的方法:
add()
set()
remove()
clear()後端
class Book(models.Model): ... authors = models.ManyToManyField(to='Author', through='Book2Author', through_fields=('book','author'))#告訴django,是和那個表多對多關聯,關聯表是什麼,關聯的字段是什麼 class Author(models.Model): ... #books = models.ManyToManyField(to='Book', through='Book2Author', through_fields=('author', 'book')) class Book2Author(models.Model): book = models.ForeignKey(to='Book') author = models.ForeignKey(to='Author') create_time = models.DateField(auto_now_add=True)#創建額外的字段
注意app
在頁面顯示分頁數據,須要用到Django分頁器組件dom
from django.core.paginator import Paginator
Paginator對象: paginator = Paginator(user_list, 10) # per_page: 每頁顯示條目數量 # count: 數據總個數 # num_pages:總頁數 # page_range:總頁數的索引範圍,如: (1,10),(1,200) # page: page對象 page對象:page=paginator.page(1) # has_next 是否有下一頁 # next_page_number 下一頁頁碼 # has_previous 是否有上一頁 # previous_page_number 上一頁頁碼 # object_list 分頁以後的數據列表 # number 當前頁 # paginator paginator對象
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 ''' book_list=Book.objects.all() paginator = Paginator(book_list, 10) page = request.GET.get('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})
<!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>
''' 顯示左5,右5,總共11個頁, 1 若是總頁碼大於11 1.1 if 當前頁碼減5小於1,要生成1到12的列表(顧頭不顧尾,共11個頁碼) page_range=range(1,12) 1.2 elif 當前頁碼+5大於總頁碼,生成當前頁碼減10,到當前頁碼加1的列表(顧頭不顧尾,共11個頁碼) page_range=range(paginator.num_pages-10,paginator.num_pages+1) 1.3 else 生成當前頁碼-5,到當前頁碼+6的列表 page_range=range(current_page_num-5,current_page_num+6) 2 其它狀況,生成的列表就是pageinator的page_range page_range=paginator.page_range '''
def index(request): book_list=Book.objects.all() paginator = Paginator(book_list, 15) page = request.GET.get('page',1) currentPage=int(page) # 若是頁數十分多時,換另一種顯示方式 if paginator.num_pages>11: if currentPage-5<1: pageRange=range(1,11) elif currentPage+5>paginator.num_pages: pageRange=range(currentPage-5,paginator.num_pages+1) else: pageRange=range(currentPage-5,currentPage+5) else: pageRange=paginator.page_range 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",locals())
def page_test(request): # book_list=[] # for i in range(100): # book=Book(name='book%s'%i,price=10+i,pub_date='2018-09-18',publish_id=1) # book_list.append(book) # Book.objects.bulk_create(book_list,10) book_list=Book.objects.all() # 生成paginator對象,傳入書籍列表,每頁10條數據 paginator=Paginator(book_list,3) # 總頁碼數 print(paginator.num_pages) # 頁碼列表 print(paginator.page_range) # 總數據 print(paginator.count) # 獲取頁面傳來的頁碼 current_page=int(request.GET.get('page',1)) page_range=[] # 左5 右5 # 獲取頁面傳來的頁碼的page對象 try: page=paginator.page(current_page) # print(page.has_next()) #是否有下一頁 # print(page.next_page_number()) #下一頁的頁碼 # print(page.has_previous()) #是否有上一頁 # print(page.previous_page_number()) #上一頁的頁碼 # 循環打印出當頁對象 for i in page: print(i) except Exception as e: current_page=1 page = paginator.page(1) if paginator.num_pages>11: if current_page+5>paginator.num_pages: page_range=range(paginator.num_pages-10,paginator.num_pages+1) elif current_page-5<1: page_range=range(1,12) else: page_range=range(current_page-5,current_page+6) else: page_range=paginator.page_range return render(request,'page_test.html',locals())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <title>Title</title> </head> <body> <ul> {% for foo in page %} <li>{{ foo.name }}</li> {% endfor %} </ul> <nav aria-label="Page navigation"> <ul class="pagination"> {% if page.has_previous %} <li> <a href="/page_test/?page={{ page.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">上一頁</span> </a> </li> {% else %} <li class="disabled"> <a href="#" aria-label="Previous"> <span aria-hidden="true">上一頁</span> </a> </li> {% endif %} {% for foo in page_range %} {% if current_page == foo %} <li class="active"><a href="/page_test/?page={{ foo }}">{{ foo }}</a></li> {% else %} <li><a href="/page_test/?page={{ foo }}">{{ foo }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li> <a href="/page_test/?page={{ page.next_page_number }}" aria-label="Next"> <span aria-hidden="true">下一頁</span> </a> </li> {% else %} <li class="disabled"> <a href="#" aria-label="Next"> <span aria-hidden="true">下一頁</span> </a> </li> {% endif %} </ul> </nav> </body> </html>