ページ分割 (Paginator)

Django はページ分割されたデータを管理するのに役立ついくつかのクラスを提供しています。これらのクラスは django/core/paginator.py にあります。

例については ページ分割 (Pagination) のトピックガイド を参照してください。

Paginator class

class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None)[ソース]

Paginator(ページネーター)は len() の使用時、または直接イテレートしたときは Page のシーケンスのように動作します。

Paginator.object_list

必須です。リスト、タプル、QuerySet、または count() または __len__() メソッドを持つその他のスライス可能なオブジェクト。一貫したページ分割のためには、QuerySet は順序付けされるべきです。たとえば、order_by() 句を使用するか、モデル上のデフォルトの ordering で行います。

巨大な QuerySet のページ分割によるパフォーマンス上の問題

非常に多数のアイテムを持つ QuerySet を使用した場合、数の大きいページをリクエストしたときに、データベースによっては速度が低下する場合があります。これは、OFFSET 数を数えるために必要な LIMIT/OFFSET クエリの処理時間が、ページ数が増えるにつれて長くなってしまうためです。

Paginator.per_page

必須です。ページ上に含めるアイテムの最大数で、孤立アイテムは含みません(以下の orphans オプション引数を参照)。

Paginator.orphans

Optional. Use this when you don't want to have a last page with very few items. If the last page would normally have a number of items less than or equal to orphans, then those items will be added to the previous page (which becomes the last page) instead of leaving the items on a page by themselves. For example, with 23 items, per_page=10, and orphans=3, there will be two pages; the first page with 10 items and the second (and last) page with 13 items. orphans defaults to zero, which means pages are never combined and the last page may have one item. orphans should be less than the per_page value.

Deprecated since version 6.0: Support for the orphans argument being larger than or equal to the per_page argument is deprecated.

Paginator.allow_empty_first_page

Optional. Whether or not the first page is allowed to be empty. If False and object_list is empty, then an EmptyPage error will be raised.

Paginator.error_messages

error_messages 引数を指定すると、paginator がデフォルトで返すメッセージを上書きできます。オーバーライドしたいエラーメッセージにマッチするキーを持つ辞書を渡します。使用可能なエラーメッセージのキーは invalid_page, min_page, no_results です。

たとえば、デフォルトのエラーメッセージは以下のようなものです:

>>> from django.core.paginator import Paginator
>>> paginator = Paginator([1, 2, 3], 2)
>>> paginator.page(5)
Traceback (most recent call last):
  ...
EmptyPage: That page contains no results

そしてこれがカスタムエラーメッセージです:

>>> paginator = Paginator(
...     [1, 2, 3],
...     2,
...     error_messages={"no_results": "Page does not exist"},
... )
>>> paginator.page(5)
Traceback (most recent call last):
  ...
EmptyPage: Page does not exist

メソッド

Paginator.get_page(number)[ソース]

1から始まるインデックスをもつ Page オブジェクトを返します。このオブジェクトは、範囲外のページ数や無効なページ数もハンドリングします。

与えられた値が数字でなかった場合は、最初のページを返します。ページ数が負の数や全体のページ数より大きかった場合は、最後のページを返します。

Paginator(..., allow_empty_first_page=False) を指定し、 object_list が空の場合にのみ EmptyPage 例外を発生させます。

Paginator.page(number)[ソース]

1から始まるインデックスを持つ Page オブジェクトを返します。数値 numberint() を呼び出して整数に変換できない場合、 PageNotAnInteger を発生させます。指定されたページ番号が存在しない場合、 EmptyPage を発生させます。

Paginator.get_elided_page_range(number, *, on_each_side=3, on_ends=2)[ソース]

Paginator.page_range に似た1から始まるページ番号のリストを返しますが、 Paginator.num_pages が大きい場合は、現在のページ番号のどちらか一方または両方に省略記号を追加します。

現在のページ番号の両側に含めるページ数は on_each_side 引数で決まり、デフォルトは3です。

ページ範囲の最初と最後に含めるページ数は on_ends 引数で指定します。デフォルトは2です。

たとえば、on_each_sideon_ends をデフォルトの値で設定した場合、現在のページが10で50ページある場合、ページ範囲は [1, 2, '...', 7, 8, 9, 10, 11, 12, 13, '...', 49, 50] となります。これにより、現在のページの左側に7、8、9ページ、右側に11、12、13ページが、また、最初に1、2ページ、最後に49、50ページが表示されます。

指定されたページ番号が存在しない場合は InvalidPage を発生させます。

属性

Paginator.ELLIPSIS

get_elided_page_range() によって返されるページ範囲において、ページ番号の代わりに使用される翻訳可能な文字列です。デフォルトは '...' です。

Paginator.count[ソース]

全ページにわたるオブジェクトの総数。

注釈

オブジェクトリスト object_list に含まれるオブジェクトの数を決定する場合、 Paginator はまず object_list.count() を呼び出します。もし object_listcount() メソッドがなければ、 Paginatorlen(object_list) を使用します。これにより、 QuerySet などのオブジェクトは、より効率的な count() メソッドを使用できます。

Paginator.num_pages[ソース]

トータルのページ数

Paginator.page_range[ソース]

1から始まるページ数の範囲のイテレータです。たとえば、[1, 2, 3, 4] を生成します。

AsyncPaginator class

New in Django 6.0.
class AsyncPaginator(object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None)[ソース]

Asynchronous version of Paginator.

AsyncPaginator has the same attributes and signatures as Paginator, with the following exceptions:

  • The attribute Paginator.count is supported as an asynchronous method AsyncPaginator.acount().

  • The attribute Paginator.num_pages is supported as an asynchronous method AsyncPaginator.anum_pages().

  • The attribute Paginator.page_range is supported as an asynchronous method AsyncPaginator.apage_range().

AsyncPaginator has asynchronous versions of the same methods as Paginator, using an a prefix - for example, use await async_paginator.aget_page(number) rather than paginator.get_page(number).

Page クラス

通常は Page オブジェクトを手動で構築することはありません。 Paginator をイテレートするか、 Paginator.page() を使ってオブジェクトを取得します。

class Page(object_list, number, paginator)[ソース]

1つのページは、len() を使ったり直接イテレーションした時、Page.object_list のシーケンスのように動作します。

メソッド

Page.has_next()[ソース]

次のページが存在する時、True を返します。

Page.has_previous()[ソース]

前のページが存在する時、True を返します。

Page.has_other_pages()[ソース]

次のページ または 前のページがある場合、 True を返します。

Page.next_page_number()[ソース]

次のページ数を返します。次のページが存在しないときは InvalidPage 例外を起こします。

Page.previous_page_number()[ソース]

前のページ数を返します。前のページが存在しないときは InvalidPage 例外を起こします。

Page.start_index()[ソース]

ページ上の最初のオブジェクトに対する、1から始まるインデックスを返します。これは、ページネータのリストに含まれる全オブジェクトに対するインデックスです。たとえば、5個のオブジェクトのリストを各ページ2オブジェクトでページ分割している場合、2ページ目の start_index()3 を返すでしょう。

Page.end_index()[ソース]

ページ上の最後のオブジェクトに対する、1から始まるインデックスを返します。これは、ページネータのリストに含まれる全オブジェクトに対するインデックスです。たとえば、5個のオブジェクトのリストを各ページ2オブジェクトでページ分割している場合、2ページ目の end_index()4 を返すでしょう。

属性

Page.object_list

当該のページに含まれるオブジェクトのリストです。

Page.number

1から数えた現在のページのページ数です。

Page.paginator

関連する Paginator オブジェクトです。

AsyncPage class

New in Django 6.0.
class AsyncPage(object_list, number, paginator)[ソース]

Asynchronous version of Page.

AsyncPage has the same attributes and signatures as Page, as well as asynchronous versions of all the same methods, using an a prefix - for example, use await async_page.ahas_next() rather than page.has_next().

AsyncPage has the following additional method:

aget_object_list()

Returns AsyncPage.object_list as a list. This method must be awaited before AsyncPage can be treated as a sequence of AsyncPage.object_list.

例外

exception InvalidPage[ソース]

pagenator に無効なページ数が渡された時に発生する例外のベースクラスです。

Paginator.page() メソッドは、リクエストされたページが無効 (つまり整数ではない) か、オブジェクトが含まれていない場合に例外を発生させます。通常、 InvalidPage 例外をキャッチすれば十分ですが、より詳細に例外をキャッチしたい場合は、以下のいずれかの例外をキャッチします:

exception PageNotAnInteger[ソース]

page() に整数でない値が与えられた時に発生します。

exception EmptyPage[ソース]

page() に有効な値が与えられているが、そのページにオブジェクトが存在しない場合に発生します。

どちらの例外も InvalidPage のサブクラスなので、 except InvalidPage で処理できます。