首先需要明确的是,get请求/post请求都可以携带参数,所以在朝后端发送数据时,可以携带一个参数告诉后端我们想看第几页的数据。
还有一点就是,queryset对象支持索引和切片操作,但是不支持负数索引情况。
后端通过get方式实现分页功能,每次切换页的时候,会刷新页面。
后端通过post方式实现分页功能,每次切换页的时候,不会刷新页面,只会重新渲染下一页的内容。
简单推导:
这里的推导在get方法中不需要用,有封装好的代码,在post方法中,需要用到下面的推导
current_page = request.GET.get("page",1) # 获取用户想访问的页码(默认为 1 )
try:
current_page = int(current_page)
except Exception as e:
current_page = 1
# 前端传过来的数据类型为字符串,所以要做异常捕获,将字符串转为整形
# 还需要定义页面到底展示几条数据
per_page_num = 10 # 一页展示10条数据
# 需要对总数据进行切片操作 需要确定切片起始位置和终止位置
start_page = ?
end_page = ?
"""
下面需要研究current_page、per_page_num、start_page、end_page四个参数之间的数据关系
per_page_num = 10
current_page start_page end_page
1 0 10
2 10 20
3 20 30
4 30 40
per_page_num = 5
current_page start_page end_page
1 0 5
2 5 10
3 10 15
4 15 20
"""
可以很明显的看出规律
start_page = (current_page - 1) * per_page_num
# 开始条数为 :(要看的页数-1)*每页展示的条数
end_page = current_page* per_page_num
# 结束条数为 : (要看的页数)*每页展示的条数
get方法实现分页器功能:
1 将下面代码直接复制:
class Pagination(object):
def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
"""
封装分页相关数据
:param current_page: 当前页
:param all_count: 数据库中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数
"""
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)
2 上面代码的使用方法
1 在前端
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
{% for book in page_queryset %}
<p>{{ book.title }}</p>
{% endfor %}
{{ page_obj.page_html|safe }}
# ## 只需要这一句就可以,上面的的for循环是要分页的数据
</div>
</div>
</div>
2 在后端
from utils.mypage import Pagination
def get_book(request):
book_list = models.Book.objects.all()
current_page = request.GET.get("page",1)
try:
current_page = int(current_page)
except Exception:
current_page = 1
# 前端传来的数据为字符串,所以后端异常捕获,为字符串的话转为int类型
all_count = book_list.count()
page_obj = Pagination(current_page=current_page,all_count=all_count,per_page_num=10)
page_queryset = book_list[page_obj.start:page_obj.end]
return render(request,'booklist.html',locals())
post方法实现分页器功能
1 直接复制下面的代码(固定模板)
# 直接拷贝用就可以了
class Pagination(object):
def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
"""
封装分页相关数据
:param current_page: 当前页
: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="javascript:;" class="btn_page" current_page="%s">%s</a></li>' % (i, i)
else:
temp = '<li><a href="javascript:;" class="btn_page" current_page="%s">%s</a></li>' % (i,i)
page_html_list.append(temp)
# post方法实现分页器,主要通过上面这一段代码实现,首先将a标签的跳转消除掉,
#然后给class="btn_page" 绑定点击事件,通过ajax重新渲染分页内的数据,实现不刷新页面,从而达到换页的功能
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)
2 上面代码的使用方法。
1在前端
评论区分页开始
<body>
<div class="pull-right">
{{ page_obj.page_html|safe }}
</div>
</body>
<script>
// 评论列表分页绑定点击事件
$('.btn_page').click(function () {
// 获取当前点了第几页
var current_page = $(this).attr('current_page')
var article_id = {{ article_obj.pk }}
$('.active').removeClass('active');
$(this).parent().addClass('active');
$.ajax({
url: '/comment_page/',
type: 'post',
data: {
current_page: current_page,
'article_id': article_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (args) {
let html = '';
if (args.code == 200) { //重新渲染一遍楼层页面,
$.each(args.data, function (index, obj) {
html +=`<li class="list-group-item">
<span style="margin-right: 10px"># ${obj.forloop}楼</span>
<span style="margin-right: 10px">${obj.comment_time}</span>
<span style="margin-right: 10px">${obj.username}</span>
<span style="margin-right: 10px" class="pull-right"><a href="javascript:;"
comment_username="${obj.username}"
comment_id='${obj.pk}'
class="reply">回复</a></span>
<div class="content" style="margin-left: 14px">
${obj.content}
</div>
</li>`
});
$('.list-group').html(html);
}
}
})
})
</script>
2 在后端
如果整个项目中多个地方需要用到分页功能,可以将上面的固定模板加入到utils文件夹,utils文件夹内可以放一些通用 的辅助函数,工具类和可重用的代码片段,这些片段不属于特定的模型,视图或者其他部分,可以被多个部分共享和复用。
# 评论区分页
from utils.mypage1 import Pagination
page_obj = Pagination(current_page=request.GET.get('page', 1),
all_count=comment_list.count(), per_page_num=5)
comment_list = comment_list[page_obj.start:page_obj.end]
def comment_page(request):
# 根据当前第几页查询当前页的评论列表数据
if request.method == 'POST':
back_dic = {'code': 200, 'msg': '查询成功'}
# 接收参数(点的第几页)
article_id = request.POST.get('article_id')
current_page = request.POST.get('current_page') # 2
try:
current_page = int(current_page)
except Exception:
current_page = 1
# 每页显示的条数
per_page_num = 5
start_page = (current_page - 1) * per_page_num
end_page = current_page * per_page_num
# 查询评论列表数据
comment_list = models.Comment.objects.filter(article_id=article_id).all()[start_page:end_page] # queryset对象
comment_list_obj = [] # [{},{},{}]
i = current_page * per_page_num - (per_page_num - 1) # 翻页后顺序依次相加
for comment in comment_list:
comment_list_obj.append({
'forloop': i,
'pk': comment.pk,
'comment_time': comment.comment_time,
'username': comment.user.username,
'content': comment.content
})
i += 1
back_dic['data'] = comment_list_obj
return JsonResponse(back_dic)