App下載

Django如何實(shí)現(xiàn)翻頁?代碼詳解!

來源: 執(zhí)手不憶殤 2021-07-15 09:21:31 瀏覽數(shù) (2196)
反饋

對(duì)于web應(yīng)用開發(fā)而言,有一項(xiàng)功能是相當(dāng)常見的,那就是分頁,而這項(xiàng)功能最關(guān)鍵的作用,就是實(shí)現(xiàn)將數(shù)據(jù)分成一頁一頁的效果,這樣每次就能閱讀有限數(shù)量的數(shù)據(jù),既降低了服務(wù)器壓力又提高了閱讀效率,而分頁功能的實(shí)現(xiàn)必須實(shí)現(xiàn)兩個(gè)小功能,分別是數(shù)據(jù)分頁和翻頁功能,接下來小編就以Django為例介紹一下Django如何實(shí)線分頁,以及Django如何實(shí)現(xiàn)翻頁功能吧。

一、views模塊導(dǎo)入Paginator類實(shí)現(xiàn)數(shù)據(jù)分頁

ApiTest/apiviews.py

每行都加了注釋,希望有助于理解。

from django.shortcuts import render
from ApiTest.models import ApiTest
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage


@login_required
def api_test_manage(request):
    username = request.session.get('user', '')
    # 獲取所有接口測(cè)試數(shù)據(jù)
    apitest_list = ApiTest.objects.all().order_by('id')
    # 生成Paginator對(duì)象對(duì)數(shù)據(jù)分頁,每頁顯示10條數(shù)據(jù)
    paginator = Paginator(apitest_list,10)
    # 使用request.GET.get()函數(shù)獲取url中的page參數(shù)的數(shù)值。默認(rèn)第1頁
    page = request.GET.get('page', 1)
    # 把獲取的當(dāng)前頁碼數(shù)轉(zhuǎn)換成整數(shù)類型
    current_page = int(page)
    try:
     # 獲取查詢頁數(shù)的接口數(shù)據(jù)列表,page()函數(shù)會(huì)判斷page實(shí)參是否是有效數(shù)字。page()函數(shù)源碼附在文章的最后
        apitest_list = paginator.page(page)
    except PageNotAnInteger:
        apitest_list = paginator.page(1)
    except (EmptyPage, InvalidPage):
     # paginator.num_pages
        apitest_list = paginator.page(paginator.num_pages)
    return render(request, "apitest_manage.html", {'user': username, 'apitests': apitest_list})

二、將views的數(shù)據(jù)渲染到前端模板上

在對(duì)應(yīng)的html文件中加入此段代碼即可。

<div class="container">
    <ul class="pagination" id="pager">
        {# 上一頁鏈接 #}
        {% if apitests.has_previous %}
        <li class="previous"><a href="/apitest_manage/?page={{ apitests.previous_page_number }}" rel="external nofollow" >上一頁</a></li>
        {% else %}
        <li class="previous disabled"><a href="#" rel="external nofollow"  rel="external nofollow" >上一頁</a></li>
        {% endif %}

        {# 中間數(shù)字顯示 #}
        {%  for num in apitests.paginator.page_range %}
            {%  if num == currentPage %}
                <li class="item active"><a href="/apitest_manage/?page={{ num }}" rel="external nofollow"  rel="external nofollow" >{{ num }}</a></li>
            {% else %}
                <li class="item"><a href="/apitest_manage/?page={{ num }}" rel="external nofollow"  rel="external nofollow" >{{ num }}</a></li>
            {% endif %}
        {% endfor %}

        {# 下一頁鏈接 #}
        {% if apitests.has_next %}   {# 如果有下一頁,則正常顯示下一頁鏈接 #}
            <li class="next"><a href="/apitest_manage/?page={{ apitests.next_page_number }}" rel="external nofollow" >下一頁</a></li>
        {% else %}
            <li class="next disabled"><a href="#" rel="external nofollow"  rel="external nofollow" >下一頁</a></li>
        {% endif %}

    </ul>
</div>

三、效果展示

分頁效果

四、Paginator類源碼

此類主要用在views文件

class Paginator:
    def __init__(self, object_list, per_page, orphans=0,
                 allow_empty_first_page=True):
        self.object_list = object_list
        self._check_object_list_is_ordered()
        self.per_page = int(per_page)
        self.orphans = int(orphans)
        self.allow_empty_first_page = allow_empty_first_page

    def validate_number(self, number):
        """Validate the given 1-based page number."""
        try:
            if isinstance(number, float) and not number.is_integer():
                raise ValueError
            number = int(number)
        except (TypeError, ValueError):
            raise PageNotAnInteger(_('That page number is not an integer'))
        if number < 1:
            raise EmptyPage(_('That page number is less than 1'))
        if number > self.num_pages:
            if number == 1 and self.allow_empty_first_page:
                pass
            else:
                raise EmptyPage(_('That page contains no results'))
        return number

    def get_page(self, number):
        """
        Return a valid page, even if the page argument isn't a number or isn't
        in range.
        """
        try:
            number = self.validate_number(number)
        except PageNotAnInteger:
            number = 1
        except EmptyPage:
            number = self.num_pages
        return self.page(number)

    def page(self, number):
        """Return a Page object for the given 1-based page number."""
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        if top + self.orphans >= self.count:
            top = self.count
        return self._get_page(self.object_list[bottom:top], number, self)

    def _get_page(self, *args, **kwargs):
        """
        Return an instance of a single page.

        This hook can be used by subclasses to use an alternative to the
        standard :cls:`Page` object.
        """
        return Page(*args, **kwargs)

    @cached_property
    def count(self):
        """Return the total number of objects, across all pages."""
        c = getattr(self.object_list, 'count', None)
        if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c):
            return c()
        return len(self.object_list)

    @cached_property
    def num_pages(self):
        """Return the total number of pages."""
        if self.count == 0 and not self.allow_empty_first_page:
            return 0
        hits = max(1, self.count - self.orphans)
        return ceil(hits / self.per_page)

    @property
    def page_range(self):
        """
        Return a 1-based range of pages for iterating through within
        a template for loop.
        """
        return range(1, self.num_pages + 1)

    def _check_object_list_is_ordered(self):
        """
        Warn if self.object_list is unordered (typically a QuerySet).
        """
        ordered = getattr(self.object_list, 'ordered', None)
        if ordered is not None and not ordered:
            obj_list_repr = (
                '{} {}'.format(self.object_list.model, self.object_list.__class__.__name__)
                if hasattr(self.object_list, 'model')
                else '{!r}'.format(self.object_list)
            )
            warnings.warn(
                'Pagination may yield inconsistent results with an unordered '
                'object_list: {}.'.format(obj_list_repr),
                UnorderedObjectListWarning,
                stacklevel=3
            )

五、Page類源碼

此類主要用在html文件

class Page(collections.abc.Sequence):

    def __init__(self, object_list, number, paginator):
        self.object_list = object_list
        self.number = number
        self.paginator = paginator

    def __repr__(self):
        return '<Page %s of %s>' % (self.number, self.paginator.num_pages)

    def __len__(self):
        return len(self.object_list)

    def __getitem__(self, index):
        if not isinstance(index, (int, slice)):
            raise TypeError(
                'Page indices must be integers or slices, not %s.'
                % type(index).__name__
            )
        # The object_list is converted to a list so that if it was a QuerySet
        # it won't be a database hit per __getitem__.
        if not isinstance(self.object_list, list):
            self.object_list = list(self.object_list)
        return self.object_list[index]

    def has_next(self):
        return self.number < self.paginator.num_pages

    def has_previous(self):
        return self.number > 1

    def has_other_pages(self):
        return self.has_previous() or self.has_next()

    def next_page_number(self):
        return self.paginator.validate_number(self.number + 1)

    def previous_page_number(self):
        return self.paginator.validate_number(self.number - 1)

    def start_index(self):
        """
        Return the 1-based index of the first object on this page,
        relative to total objects in the paginator.
        """
        # Special case, return zero if no items.
        if self.paginator.count == 0:
            return 0
        return (self.paginator.per_page * (self.number - 1)) + 1

    def end_index(self):
        """
        Return the 1-based index of the last object on this page,
        relative to total objects found (hits).
        """
        # Special case for the last page because there can be orphans.
        if self.number == self.paginator.num_pages:
            return self.paginator.count
        return self.number * self.paginator.per_page

小結(jié)

到此這篇關(guān)于Django如何實(shí)現(xiàn)翻頁的文章就介紹到這了,更多Django相關(guān)內(nèi)容請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章。希望大家以后多多支持W3Cschool!


0 人點(diǎn)贊