pager.py:
"""
如果想要使用分页,需要以下两个步骤
def xxx():
queryset = models.Customer.objects.filter(active=1).select_related('level', 'creator') # select_related主动跨表
pager = Pagination(request, queryset)
context = {
'queryset': queryset[pager.start: pager.end],
'pager_string': pager.html(),
}
return render(request, 'customer_list.html', context)
页面上:
{% for row in queryset %}
{{row.id}}
...
{% endfor %}
<ul class="pagination">
{{ pager_string }}
</ul>
"""
from django.utils.safestring import mark_safe
class Pagination(object):
"""分页"""
def __init__(self, request, queryset, per_page_count=10):
total_count = queryset.count() # 总数据条数
# 计算出总共有多少页面
self.total_count = total_count
self.total_page, div = divmod(total_count, per_page_count)
if div:
self.total_page += 1
page = request.GET.get('page')
if not page:
page = 1
else:
if not page.isdecimal():
page = 1
else:
page = int(page)
if page < 0:
page = 1
else:
if page > self.total_page:
page = self.total_page
self.page = page
self.per_page_count = per_page_count
self.start = (page - 1) * per_page_count
self.end = page * per_page_count
def html(self):
pager_list = []
# 极值问题:总共的页码数量
if self.total_page <= 11:
start_page = 1
end_page = self.total_page
else:
# 总页码比较多,判断当前页 <=6 : 1~11
if self.page <= 6:
start_page = 1
end_page = 11
else:
if (self.page + 5) > self.total_page:
start_page = self.total_page - 10
end_page = self.total_page
else:
start_page = self.page - 5
end_page = self.page + 5
for i in range(start_page, end_page + 1):
if i == self.page:
item = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
else:
item = '<li><a href="?page={}">{}</a></li>'.format(i, i)
pager_list.append(item)
pager_string = mark_safe(''.join(pager_list))
return pager_string
标签:count,self,30,queryset,Django,组件,total,pager,page
From: https://www.cnblogs.com/mimiICC/p/16776334.html