Django의 페이지
1. 대량 데이터 가져오기
book_list = []
for i in range(100):
    book_obj = Book(title="Book_%s" % i, price=i * i)
    book_list.append(book_obj)
Book.objects.bulk_create(book_list)2. 페이지 나누기
views.py 파일 내용:
from django.shortcuts import render,HttpResponse
from app01.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
    '''
      :
    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)
    
    print(page2.has_next())            #      
    print(page2.next_page_number())        #      
    print(page2.has_previous())          #      
    print(page2.previous_page_number())      #      
    
    #   
    #page=paginator.page(12)   # error:EmptyPage
    #page=paginator.page("z")   # error:PageNotAnInteger
    '''
    book_list=Book.objects.all()
    paginator = Paginator(book_list, 10)       #    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",{"book_list":book_list,"paginator":paginator,"currentPage":currentPage})index.html 파일 내용:
html>
    
    Title 
    
       
    
        {% for book in book_list %}
             - {{ book.title }} -----{{ book.price }}{% endfor %}
3. 대량의 페이지 번호 목록을 표시하는 데 최적화
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>30:
        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())2. 사용자 정의 페이지
"""
        :
    obj = Pagination(request.GET.get('page',1),len(USER_LIST),request.path_info)
    page_user_list = USER_LIST[obj.start:obj.end]
    page_html = obj.page_html()
    return render(request,'index.html',{'users':page_user_list,'page_html':page_html})
"""
class Pagination(object):
    def __init__(self,current_page,all_count,base_url,per_page_num=2,pager_count=11):
        """
                
        :param current_page:    
        :param all_count:              
        :param per_page_num:          
        :param base_url:       URL  
        :param pager_count:           
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1
        if current_page <1:
            current_page = 1
        self.current_page = current_page
        self.all_count = all_count
        self.per_page_num = per_page_num
        self.base_url = base_url
        #    
        all_pager, tmp = divmod(all_count, per_page_num)
        if tmp:
            all_pager += 1
        self.all_pager = all_pager
        self.pager_count = pager_count
        self.pager_count_half = int((pager_count - 1) / 2)
    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num
    @property
    def end(self):
        return self.current_page * self.per_page_num
    def page_html(self):
        #        11
        else:
            #      <=       11/2   
            if self.current_page <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1
            #      5
            else:
                #       
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1
        page_html_list = []
        first_page = 'page_html_list.append(first_page)
if self.current_page <= 1:
prev_page = '
else:
prev_page = '
page_html_list.append(prev_page)
for i in range(pager_start, pager_end):
if i == self.current_page:
temp = '
else:
temp = '
page_html_list.append(temp)
if self.current_page >= self.all_pager:
next_page = '
else:
next_page = '
page_html_list.append(next_page)
last_page = '
page_html_list.append(last_page)
return ''.join(page_html_list)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Django 라우팅 계층 URLconf 작용 및 원리 해석URL 구성(URLconf)은 Django가 지원하는 웹 사이트의 디렉토리와 같습니다.그것의 본질은 URL과 이 URL을 호출할 보기 함수 사이의 맵표입니다. 위의 예제에서는 URL의 값을 캡처하고 위치 매개 변수로...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.