[Django]ページネーション

Djangoでは「Paginator」というクラスが用意されている
– 変数 = Paginator(コレクション、レコード数)
– 指定ページのレコードを取り出すには「get_page」メソッドを使う

### Paginatorを使用する
/hello/urls.py

1
2
3
4
5
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:num>', views.index, name='index'),
    //
]

※ path(”, views.index, name=’index’)は削除しない

/hello/views.py

1
2
3
4
5
6
7
8
9
10
11
from django.core.paginator import Paginator
 
def index(request, num=1):
    data = Friend.objects.all()
    page = Paginator(data, 3)
    params = {
        'title': 'Hello',
        'message': '',
        'data': page.get_page(num),
    }      
    return render(request, 'hello/index.html', params)

Paginator(data, 3)でQuerySetオブジェクトからPaginatorインスタンスを作成する

/hello/templates/hello/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<body class="container">
    <h1 class="display-4 text-primary">{{title}}</h1>
    <p>{{message|safe}}</p>
    <table class="table">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>age</th>
            <th>mail</th>
            <th>birth</th>
        </tr>
    {% for item in data %}
        <tr>
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>{{item.mail}}</td>
            <td>{{item.birthday}}</td>
        </tr>
    {% endfor %}
    </table>
    <ul class="pagination">
        {% if data.has_previous %}
        <li class="page-item">
            <a class="page-link" href="{% url 'index' %}">
            &laquo; first</a>
        </li>
        <li class="page-item">
            <a class="page-link" href="{% url 'index' %}{{data.previous_page_number}}">
            &laquo; prev</a>
        </li>
        {% else %}
        <li class="page-item">
            <a class="page-link">
            &laquo; first</a>
        </li>
        <li class="page-item">
            <a class="page-link">
            &laquo; prev</a>
        </li>
        {% endif %}
        <li class="page-item">
            <a class="page-link">
            {{data.number}}/{{data.paginator.num_pages}}</a>
        </li>
        {% if data.has_next %}
        <li class="page-item">
            <a class="page-link" href="{% url 'index' %}{{data.next_page_number}}">
            next &raquo;</a>
        </li>
        <li class="page-item">
            <a class="page-link" href="{% url 'index' %}{{data.paginator.num_pages}}">
            last &raquo;</a>
        </li>
        {% else %}
        <li class="page-item">
            <a class="page-link">next &raquo;</a>
        </li>
        <li class="page-item">
            <a class="page-link">last &raquo;</a>
        </li>
        {% endif %}
    </ul>
</body>

これは凄い