Django元件之 分頁器

2021-08-27 08:51:41 字數 3043 閱讀 8767

django自帶分頁器(paginator), 用起來非常方便。怕自己寫的出bug,可以使用現成的~

''' 批量匯入資料:

booklist=

for i in range(100):

book.objects.bulk_create(booklist)

''''''分頁器的使用:

book_list=book.objects.all()

paginator = paginator(book_list, 10)

print("count:",paginator.count) #資料總數

print("num_pages",paginator.num_pages) #總頁數

print("page_range",paginator.page_range) #頁碼的列表

page1=paginator.page(1) #第1頁的page物件

for i in page1: #遍歷第1頁的所有資料物件

print(i)

print(page1.object_list) #第1頁的所有資料

page2=paginator.page(2)

# 拋錯

#page=paginator.page(12) # error:emptypage

#page=paginator.page("z") # error:pagenotaninteger

'''book_list=book.objects.all()

paginator = paginator(book_list, 10)

page = request.get.get('page',1)

currentpage=int(page)

try:

print(page)

book_list = paginator.page(page)

except pagenotaninteger:

book_list = paginator.page(1)

except emptypage:

book_list = paginator.page(paginator.num_pages)

return render(request,"index.html",)

doctype

html>

lang="en">

charset="utf-8">

titletitle>

rel="stylesheet"

href=""

integrity="sha384-bvyiisifek1dgmjrakycuhahrg32omucww7on3rydg4va+pmstsz/k68vbdejh4u"

crossorigin="anonymous">

head>

class="container">

分頁器h4>

}-----

}li>

ul>

class="pagination"

id="pager">

class="previous">

href="/index/?page=

}li>

class="previous disabled">

li>

class="item active">

href="/index/?page=

}">

}a>

li>

class="item">

href="/index/?page=

}">

}a>

li>

class="next">

href="/index/?page=

}li>

class="next disabled">

li>

ul>

div>

body>

html>

def

index

(request):

book_list=book.objects.all()

paginator = paginator(book_list, 15)

page = request.get.get('page',1)

currentpage=int(page)

# 如果頁數十分多時,換另外一種顯示方式

if paginator.num_pages>11:

if currentpage-5

<1:

pagerange=range(1,11)

elif currentpage+5>paginator.num_pages:

pagerange=range(currentpage-5,paginator.num_pages+1)

else:

pagerange=range(currentpage-5,currentpage+5)

else:

pagerange=paginator.page_range

try:

print(page)

book_list = paginator.page(page)

except pagenotaninteger:

book_list = paginator.page(1)

except emptypage:

book_list = paginator.page(paginator.num_pages)

return render(request,"index.html",locals())

django之分頁器元件

1,配置路由,在模板層建立表模型 2,在檢視層圍標新增資料 def index request 先造成100本書,放到列表中 ll for i in range 100 批量插入,兩個引數,第乙個是物件列表,第二個是一次插入的資料量,不填,預設一次全插入 models.book.objects.bu...

Django元件 分頁器

批量匯入資料 booklist for i in range 100 book.objects.bulk create booklist 分頁器的使用 book list book.objects.all paginator paginator book list,10 print count pa...

Django元件 分頁器

批量匯入資料 booklist for i in range 100 book.objects.bulk create booklist 分頁器的使用 book list book.objects.all paginator paginator book list,10 print count pa...