1. 分页的基础
views.py
# 分页代码 page = int(request.GET.get('page', 1)) paeg_size = 10 start = (page - 1) * paeg_size end = page * paeg_size # 查询结果输出 number_lits = models.Number.objects.filter(**data_dict).order_by('-price')[start:end]
2. html
<nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="?page=1">1</a></li> <li><a href="?page=2">2</a></li> <li><a href="?page=3">3</a></li> <li><a href="?page=4">4</a></li> <li><a href="?page=5">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav>
正式分页代码 (不完整):
# 分页代码 page = int(request.GET.get('page', 1)) paeg_size = 11 # 每页显示条数 start = (page - 1) * paeg_size # 开始数据 end = page * paeg_size #结束数据 # 查询数据库中所有数据的 个数 tot_count = models.Number.objects.filter(**data_dict).order_by('-price').count() # 输出结果 number_lits = models.Number.objects.filter(**data_dict).order_by('-price')[start:end] # 总页码 total_page_count, div = divmod(tot_count, paeg_size) if div: total_page_count + 1 # 页码 page_steing = ''.join(page_ste_list) 变为安全必须得导包 from django.utils.safestring import mark_safe page_ste_list = [] for i in range(1, total_page_count + 1): ele = '<li><a href="?page={}">{}</a></li>'.format(i, i) page_ste_list.append(ele) # mark_safe() 需要导包 page_steing = mark_safe(''.join(page_ste_list)) return render(request, 'number_list.html', {'number_lits': number_lits, 'search_data':search_data, 'page_steing': page_steing})