1 from django.shortcuts import render,HttpResponse 2 3 # Create your views here. 4 from app01.models import * 5 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger 6 7 def index(request): 8 9 ''' 10 批量导入数据: 11 12 Booklist=[] 13 for i in range(100): 14 Booklist.append(Book(title="book"+str(i),price=30+i*i)) 15 Book.objects.bulk_create(Booklist) 16 ''' 17 18 ''' 19 分页器的使用: 20 21 book_list=Book.objects.all() 22 23 paginator = Paginator(book_list, 10) 24 25 print("count:",paginator.count) #数据总数 26 print("num_pages",paginator.num_pages) #总页数 27 print("page_range",paginator.page_range) #页码的列表 28 29 30 31 page1=paginator.page(1) #第1页的page对象 32 for i in page1: #遍历第1页的所有数据对象 33 print(i) 34 35 print(page1.object_list) #第1页的所有数据 36 37 38 page2=paginator.page(2) 39 40 print(page2.has_next()) #是否有下一页 41 print(page2.next_page_number()) #下一页的页码 42 print(page2.has_previous()) #是否有上一页 43 print(page2.previous_page_number()) #上一页的页码 44 45 46 47 # 抛错 48 #page=paginator.page(12) # error:EmptyPage 49 50 #page=paginator.page("z") # error:PageNotAnInteger 51 52 ''' 53 54 55 book_list=Book.objects.all() 56 57 paginator = Paginator(book_list, 10) 58 page = request.GET.get('page',1) 59 currentPage=int(page) 60 61 62 try: 63 print(page) 64 book_list = paginator.page(page) 65 except PageNotAnInteger: 66 book_list = paginator.page(1) 67 except EmptyPage: 68 book_list = paginator.page(paginator.num_pages) 69 70 71 return render(request,"index.html",{"book_list":book_list,"paginator":paginator,"currentPage":currentPage})
原文:https://www.cnblogs.com/yuanchenqi/articles/9036515.html