2018年1月3日水曜日

django-tables2 の SingleTableView を利用してみる

前回は TemplateView で django-tables2 を利用した。
同様の機能として django-tables2 の SingleTableMixin を利用することができる。

以下の例では、Actor model のデータを ActorTable table の構造で表示する。なお、table_pagination は RequestConfig の paginate パラメータへ与える辞書を与えることができる。
from django_tables2 import SingleTableView
class ActorSingleTableView(SingleTableView):
    model = Actor
    table_class = ActorTable
    table_pagination = {"per_page": 20}
    template_name = "actorlistview.html"
このテーブルを表示する際、デフォルトのテンプレート変数は table になる。
テンプレート引数を他の変数に変更したい場合は、context_table_name を設定する。
from django_tables2 import SingleTableView
class ActorSingleTableView(SingleTableView):
    model = Actor
    table_class = ActorTable
    context_table_name = "actors_table"     # テンプレート変数が actors_table に変更される。
    table_pagination = {"per_page": 20}
    template_name = "actorlistview.html"
上記例の場合、Actor に格納されたデータがそのまま ActorTable の形式で表示される。
クエリを変更したい場合、いくつかの方法がある。

まず、queryset を設定する方法である。以下の例では、表示順を last_name, first_name の順にしている。
from django_tables2 import SingleTableView
class ActorSingleTableView(SingleTableView):
    queryset = Actor.objects.order_by("last_name", "first_name")
    table_class = ActorTable
    table_pagination = {"per_page": 20}
    template_name = "actorlistview.html"
get_queryset() により設定することもできる。
from django_tables2 import SingleTableView
class ActorSingleTableView(SingleTableView):
    table_class = ActorTable
    table_pagination = {"per_page": 20}
    template_name = "actorlistview.html"

    def get_queryset(self):
        return Actor.objects.order_by("last_name", "first_name")
また、同様に get_table_data() により設定することができる。
from django_tables2 import SingleTableView
class ActorSingleTableView(SingleTableView):
    model = Actor
    table_class = ActorTable
    table_pagination = {"per_page": 20}
    template_name = "actorlistview.html"

    def get_table_data(self):
        return Actor.objects.order_by("last_name", "first_name")

0 件のコメント:

コメントを投稿