Python:Django3x分页分个明白

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage


def page_results(contacts, page, page_size):
    page_size = page_size if type(page_size) is int else int(page_size)
    paginator = Paginator(contacts, page_size)
    kwargs = {
        'per_page': 0,
        'has_previous': 0,
        'number': 0,
        'num_pages': 0,
        'previous_page_number': 0,
        'next_page_number': 0,
        'count': 0,
    }
    try:
        page = page if type(page) is int else int(page)
        contacts = paginator.page(page)
        kwargs['per_page'] = contacts.paginator.per_page
        kwargs['has_previous'] = contacts.has_previous
        kwargs['number'] = contacts.number
        kwargs['num_pages'] = contacts.paginator.num_pages
        kwargs['previous_page_number'] = contacts.previous_page_number
        kwargs['next_page_number'] = contacts.next_page_number
        kwargs['count'] = contacts.paginator.count

        # TODO: 开始捕获异常
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except InvalidPage:
        # 如果请求的页数不存在, 重定向页面
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果请求的页数不在合法的页数范围内,返回结果的最后一页。
        contacts = paginator.page(paginator.num_pages)

    kwargs['per_page'] = contacts.paginator.per_page
    kwargs['has_previous'] = contacts.has_previous
    kwargs['number'] = contacts.number
    kwargs['num_pages'] = contacts.paginator.num_pages
    kwargs['previous_page_number'] = contacts.previous_page_number
    kwargs['next_page_number'] = contacts.next_page_number
    kwargs['count'] = contacts.paginator.count
    kwargs['page'] = page
    kwargs['page_size'] = page_size

    return contacts, kwargs

上一篇:双链表的增删改查


下一篇:oracle11g静默安装