Django實現基於類的分頁功能

2021-09-22 02:24:24 字數 2748 閱讀 7636

class page:

page_num = 0

total_count = 0

tartype = ""

total_page = 0 # 總頁數

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 =

'.format(self.tartype, last_page, self.category))

for i in range(page_start, page_end + 1):

if i == self.page_num:

tmp = '{}

'.format(self.tartype, i, self.category, i)

continue

tmp = '{}

'.format(self.tartype, i, self.category, i)

'.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頁時值為空。可以根據自己要實現的功能進行修改】建構函式會計算出總頁碼數並過濾掉錯誤資料。需要實現某功能是直接呼叫類方法即可。

類方法:data_start()計算出當前頁的文章的起始索引值

data_end()計算出當前頁的文章的起始索引值

page_html()返回分頁模組的html**,可直接render到前端。

實現效果:

Django 分頁的簡單實現

django分頁比較簡單,它內建了乙個paginator類.這樣對分頁的操作只需要明白這個類就ok了。def list request after range num 5 bevor range num 4 try page int request.get.get page 1 print page...

Django的分頁顯示實現

django中提供了乙個類paginator專門用來管理和處理分頁資料,所以我們在使用之前先導入好相應的類,另外這裡我們也匯入了待會會用到的處理異常的兩個類emptypage和pagenotaninteger from django.core.paginator import paginator,e...

django 實現分頁功能

分頁效果 檢視 1 coding utf 8 2 from django.shortcuts import render,get object or 404 3 from django.core.paginator import paginator,pagenotaninteger,emptypag...