models.py:
from django.db import models class Book(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title class Meta: db_table = "books"
批量创建 106 条数据
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite3.settings") import django django.setup() from app01 import models # 106 个书籍对象 objs = [models.Book(title="《Python 的故事第{}版》".format(i)) for i in range(116)] # 在数据库中批量创建, 10 次一提交 models.Book.objects.bulk_create(objs, 10)
views.py:
from django.shortcuts import render from app01 import models def book_list(request): # 从 URL 中取参数 page_num = request.GET.get("page") print(page_num, type(page_num)) page_num = int(page_num) # 定义两个变量保存数据从哪儿取到哪儿 data_start = (page_num-1)*10 data_end = page_num*10 # 书籍总数 total_count = models.Book.objects.all().count() # 每一页显示多少条数据 per_page = 10 # 总共需要多少页码来显示 total_page, m = divmod(total_count, per_page) if m: total_page += 1 all_book = models.Book.objects.all()[data_start:data_end] # 拼接 html 的分页代码 html_list = [] for i in range(1, total_page+1): tmp = '<li><a href="/book_list/?page={0}">{0}</a></li>'.format(i) html_list.append(tmp) page_html = "".join(html_list) return render(request, "book_list.html", {"books": all_book, "page_html": page_html})
book_list.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>书籍列表</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> </head> <body> <div class="container"> <table class="table table-bordered"> <thead> <tr> <th>序号</th> <th>id</th> <th>书名</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.id }}</td> <td>{{ book.title }}</td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation"> <ul class="pagination"> {{ page_html|safe }} </ul> </nav> </div> </body> </html>
运行结果: