牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Djangoのクラスベース汎用ビューでペジネータのメモ

追記2013-09-07: get_queryset

(Django1.5, Python2.7)

ページネイト, ページネイション, ページネータ, paginate, pagination, paginator のメモ

下準備

  • プロジェクト作成してDBとか設定
  • 適当にアプリ作成
$ ./manage.py startapp cars

cars app

cars/models.py
from django.db import models

class Car(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name
cars/views.py
from django.views.generic import ListView
from cars.models import Car

class CarListView(ListView):
    model = Car
    template_name = 'cars/index.html'
    context_object_name = 'cars'
    paginate_by = 5

    # ここでDBの取り方を弄れる
    def get_queryset(self):
        return Car.objects.order_by('-name')
cars/urls.py
from django.conf.urls import patterns, url
from cars.views import CarListView

urlpatterns = patterns(
    '',
    url(r'^$', CarListView.as_view()),
)
templates/cars/index.html

In your template (car_list.html), you can include a pagination section like this (we have some context variables available: is_paginated, page_obj, and paginator).

How do I use pagination with Django class based generic ListViews? - Stack Overflow

クラスベースの ListView のコンテクスト変数には is_paginated, page_obj, and paginator が入ってる(公式ドキュメントだとどこに書いてあるのかわかりにくいこれ)

<h2>Cars</h2>

<ul>
    {% for car in cars %}
    <li>{{ car.name }}</li>
    {% endfor %}
</ul>


{% if is_paginated %}

<div class="paginate">
    {% if page_obj.has_previous %}
    <span><a href="?page={{ page_obj.previous_page_number }}">previous</a></span>
    {% endif %}

    {% for page_num in page_obj.paginator.page_range %}
    {% if page_obj.number == page_num %}
    <span>{{ page_num }}</span>
    {% else %}
    <span><a href="?page={{ page_num }}">{{ page_num }}</a></span>
    {% endif %}
    {% endfor %}
    
    {% if page_obj.has_next %}
    <span><a href="?page={{ page_obj.next_page_number }}">next</a></span>
    {% endif %}
</div>

{% endif %}

確認用DB投入

$ ./manage.py syncdb

$ ./manage.py shell

>>> from cars.models import Car
>>> [Car.objects.create(name='car{num}'.format(num=num)) for num in range(1, 50)]