表模型 - django.core.paginator - 分页

index.py
import inspectfrom django.core.paginator import Paginator,PageNotAnInteger,EmptyPageclass Table_M(): def __init__(self): self.class_name = "Table_M()" def to_json(self, data, info="转成json"): try: return_data = { "id":data.id, "name":data.name, "date":data.date } return return_data except Exception as e: logger.error(info+'数据库操作失败: '+ self.class_name + inspect.currentframe().f_code.co_name + str(e)) raise def index(self,id,page,page_size): infoList=Info.objects.filter(user_id=id).order_by('id') paginator=Paginator(infoList,page_size) try: pageInfo=paginator.page(page) except PageNotAnInteger: pageInfo=paginator.page(1) except EmptyPage: pageInfo=paginator.page(paginator.num_pages) else: return_data = list(map(self.to_json, pageInfo)) return_data = { "data":return_data, "page":page, "num_pages":paginator.num_pages, # 总页数 "count":paginator.count # 总数据条数 } return return_data
index.html
<div>{% for list in pageInfo.object_list %}<div> <img src="{{ list.photo.url }}"> {% if list.title %} <h4>{{ list.title }}</h4> {% else %} <h4>相册图片</h4> {% endif %} {% if list.introduce %} <span>{{ list.introduce }}</span> {% else %}<span>暂无介绍</span> {% endif %}</div> {% endfor %} </div><div>{% if pageInfo.has_previous %} <a href="{% url 'album' id pageInfo.previous_page_number %}">上一页</a>{% endif %}{% for page in pageInfo.paginator.page_range %}{% if pageInfo.number == page %} <a href="javascript:;"> {{ page }}</a>{% else %} <a href="{% url 'album' id page %}"> {{ page }}</a> {% endif %}{% endfor %}{% if pageInfo.has_next %} <a href="{% url 'album' id pageInfo.next_page_number %}">下一页</a>{% endif %}</div>
has_next/previous()判断当前页是否存在下一页/上一页has_other_pages()判断当前页是否具有上一页或者下一页next_page_number()如果当前页存在下一页则返回下一页的页数,否则抛出EmptyPage()previous_page_number