1.插入批量数据
book_list = [] for i in range(1,101): book = Book(title="book_%s"%i,price=i*i) book_list.append(book) Book.objects.bulk_create(book_list)
2.分页器的使用
book_list = Book.objects.all() print(book_list) paginator = Paginator(book_list, 10) print(paginator.count) #对象总数 print(paginator.num_pages) #分页数 print(paginator.page_range) #range(1,11) page = paginator.page(5) #第几页的数据 for i in page: print(i) print(page.has_next()) #是否有下一页 True print(page.has_previous()) #是否有上一页 print(page.next_page_number()) #下一页是第几页 print(page.previous_page_number()) #上一页是第几页
3.服务器端
from django.core.paginator import Paginator
def index(request): book_list = Book.objects.all() paginator = Paginator(book_list,10)
try:
current_page_num = request.GET.get("page",1)
current_page = paginator.page(current_page_num)
except EmptyPage as s:
current_page_num = 1
current_page = paginator.page(1)
return render(request,"index.html",{"current_page":current_page,"paginator":paginator,"current_page_num":int(current_page_num)})
4.前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <ul> {% for book in current_page %} <li>{{ book.title }}------{{ book.price }}</li> {% endfor %} </ul> <nav aria-label="Page navigation"> <ul class="pagination"> {% if current_page.has_previous %} <li><a href="?page={{ current_page.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">上一页</span></a></li> {% else %} <li class="disabled"><a href="">上一页</a></li> {% endif %} {% for i in paginator.page_range %} {% if current_page_num == i %} <li class="active"><a href="?page={{ i }}">{{ i }}</a></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if current_page.has_next%} <li> <a href="?page={{ current_page.next_page_number }}" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> {% else %} <li class="disabled"><a href="">下一页</a></li> {% endif %} </ul> </nav> </body> </html>