Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement the custom pager for python

Shulou Source: shulou.com Published: 2022-05-31 22:40:53 10月03日 Update

This article introduces the relevant knowledge of "how to implement the python custom pager". In the operation of the actual case, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Custom pager encapsulation code

Encapsulate paging related data:

: param current_page: current page

: param all_count: the total number of data items in the database

: param per_page_num: the number of pieces of data displayed per page

: param pager_count: the maximum number of page numbers displayed

Class Pagination (object): def _ _ init__ (self, current_page, all_count, per_page_num=2, pager_count=11): try:current_page = int (current_page) except Exception as e:current_page = 1if current_page

< 1:current_page = 1self.current_page = current_pageself.all_count = all_countself.per_page_num = per_page_num# 总页码all_pager, tmp = divmod(all_count, per_page_num)if tmp:all_pager += 1self.all_pager = all_pagerself.pager_count = pager_countself.pager_count_half = int((pager_count - 1) / 2)@propertydef start(self):return (self.current_page - 1) * self.per_page_num@propertydef end(self):return self.current_page * self.per_page_numdef page_html(self):# 如果总页码 < 11个:if self.all_pager 11else:# 当前页如果= self.all_pager:next_page = '下一页'else:next_page = '下一页' % (self.current_page + 1,)page_html_list.append(next_page)last_page = '尾页' % (self.all_pager,)page_html_list.append(last_page)# 尾部添加标签page_html_list.append('''''')return ''.join(page_html_list)自定义分页器使用后端from utils.mypage import Paginationdef get_book(request):book_list = models.Book.objects.all()current_page = request.GET.get("page",1)all_count = book_list.count()page_obj = Pagination(current_page=current_page,all_count=all_count,per_page_num=10)page_queryset = book_list[page_obj.start:page_obj.end]return render(request,'booklist.html',locals())前端{% for book in page_queryset %} {{ book.title }} {% endfor %}{{ page_obj.page_html|safe }}

This is the end of the content of "how to implement the python custom pager". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Data page number content more tag knowledge previous encapsulation utility learning next number code front end dilemma actual tail situation database article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MariaDB Shulou Information Huawei Redmi