首页 > 网站 > 帮助中心 > 正文

Django实现基于类的分页功能

2024-07-09 22:41:14
字体:
来源:转载
供稿:网友

开发个人博客时往往避免不了分页功能的实现,实现方法大体上分为函数和类两种。本文基于类实现分页功能,以下是详细代码:

class Page: page_num = 0 total_count = 0 tartype = "" total_page = 0 # 总页数 per_page = 8 # 每页显示8篇文章 max_page = 11 # 每页最大展示页数选项 half_page = max_page // 2 category = "" # 标记该链接所属分类ID,首页默认为空 def __init__(self, page_num, total_count, tartype, category): """ 初始化函数:接收页码数、总数据数,计算总页码数并过滤错误页码数据 :param page_num: 页码数 :param total_count: 总数据数 :param tartype: 分类值 :param category: 所属分类ID """ self.page_num = page_num self.total_count = total_count self.tartype = tartype self.total_page, m = divmod(self.total_count, self.per_page) # 总页码数,余数为m if category:  self.category = category if m:  self.total_page += 1 if self.total_page < self.max_page:  self.max_page = self.total_page  self.half_page = self.max_page // 2 # 过滤错误get数据 if self.page_num > self.total_page:  self.page_num = self.total_page elif self.page_num < 1:  self.page_num = 1 def data_start(self): return (self.page_num - 1) * self.per_page def data_end(self): return self.page_num * self.per_page def page_html(self): # 计算页数选项 page_start = self.page_num - self.half_page page_end = self.page_num + self.half_page if page_start <= 1:  page_start = 1  page_end = self.max_page if page_end >= self.total_page:  page_end = self.total_page  page_start = self.total_page - self.max_page + 1 # 计算上一页下一页选项 if self.page_num == 1:  last_page = self.page_num  next_page = self.page_num + 1 else:  if self.page_num == self.total_page:  last_page = self.page_num - 1  next_page = self.page_num  else:  last_page = self.page_num - 1  next_page = self.page_num + 1 print(self.category) html_str_list = [] html_str_list.append('<li><a href="/{}/?page={}{}" >«</a></li>'.format(self.tartype, last_page, self.category)) for i in range(page_start, page_end + 1):  if i == self.page_num:  tmp = '<li><a class="active" href="/{}/?page={}{}" >{}</a></li>'.format(self.tartype, i, self.category, i)  html_str_list.append(tmp)  continue  tmp = '<li><a href="/{}/?page={}{}" >{}</a></li>'.format(self.tartype, i, self.category, i)  html_str_list.append(tmp) html_str_list.append('<li><a href="/{}/?page={}{}" >»</a></li>'.format(self.tartype, next_page, self.category)) page_html = "".join(html_str_list) return page_html

通过修改per_page、max_page控制每页展示的文章数和分页模块展示的最大页码数。

实现思路:创建page类对象,传入参数为page_num(当前页码数)、total_count(总文章数)、tartype(分类值)、category(所属分类ID)【注:tartpe用于区分index页还是category页,category为查询的分类ID,index页时值为空。可以根据自己要实现的功能进行修改】构造函数会计算出总页码数并过滤掉错误数据。需要实现某功能是直接调用类方法即可。

类方法:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表