Django-tables2: 列を動的に追加する直感的な方法

作成日 2012年04月17日  ·  3コメント  ·  ソース: jieter/django-tables2

進行中のすべてのメタマジックのために、私は現在使用しています:

class StatsTable(tables.Table):
   class Meta:
        orderable = False
        attrs = {'class': 'tablesorter'}

    def __init__(self, form, request, *args, **kwargs):
        rf_values = form.get_values()
        rf_annotations = form.get_annotations()
        rf_filter = form.get_filter()
        rf_calculations = form.get_calculations()                  
        data = list(
            HourlyStat.objects.filter(**rf_filter).values(*rf_values).annotate(**rf_annotations).order_by('-clicks')
        ) 
        super(StatsTable, self).__init__(data, *args, **kwargs)      
        columns = rf_values + rf_annotations.keys() + rf_calculations
        for col in columns:
            self.base_columns[col] = tables.Column()     

本当に私がこのようにそれを使用する際の唯一の問題は、それが真ん中になければならない最後にsuper()を単に呼び出すことができないという事実です。 メタクラスは実際にはそれ自体でbase_columnsを検索するのではなく、継承されたモデルでのみ検索するためだと思います。 本当にこれは、djangoフォームのself.fieldsよりもずっと厄介なようです。

最も参考になるコメント

これは奇妙です
self.base_columnsに動的列を追加するだけで、動的列を追加します。

self.base_columns['column_name'] = tables.Column()

私が厄介だと思ったのは、それを行うことで、インスタンス属性ではなくクラス属性を変更することです。そのため、リクエストに追加した列は、テーブルへの後続のすべてのリクエストで表示されます。これは、私が見つけた実際の動的列の解決策です。だった:

class ComponenteContableColumns(tables.Table):

    """Table that shows ComponentesContables as columns."""

    a_static_columns = tables.Column()

    def __init__(self, *args, **kwargs):
        # Create a copy of base_columns to restore at the end.
        self._bc = copy.deepcopy(self.base_columns)
        # Your dynamic columns added here:
        if today is 'monday':
            self.base_columns['monday'] = tables.Column()
        if today is 'tuesday':
            self.base_columns['tuesday'] = tables.Column()
        super().__init__(*args, **kwargs)
        # restore original base_column to avoid permanent columns.
        type(self).base_columns = self._bc

全てのコメント3件

これは奇妙です
self.base_columnsに動的列を追加するだけで、動的列を追加します。

self.base_columns['column_name'] = tables.Column()

私が厄介だと思ったのは、それを行うことで、インスタンス属性ではなくクラス属性を変更することです。そのため、リクエストに追加した列は、テーブルへの後続のすべてのリクエストで表示されます。これは、私が見つけた実際の動的列の解決策です。だった:

class ComponenteContableColumns(tables.Table):

    """Table that shows ComponentesContables as columns."""

    a_static_columns = tables.Column()

    def __init__(self, *args, **kwargs):
        # Create a copy of base_columns to restore at the end.
        self._bc = copy.deepcopy(self.base_columns)
        # Your dynamic columns added here:
        if today is 'monday':
            self.base_columns['monday'] = tables.Column()
        if today is 'tuesday':
            self.base_columns['tuesday'] = tables.Column()
        super().__init__(*args, **kwargs)
        # restore original base_column to avoid permanent columns.
        type(self).base_columns = self._bc

私は@jmfedericoと同じ問題を

参考までに私のテーブルクラスです

class ActivitySummaryTable(TableWithRawData):
    activity = tables.Column(verbose_name=_('Activity'), orderable=False)
    # the rest of the columns will be added based on the filter provided

    def __init__(self, extra_cols, *args, **kwargs):
        """Pass in a list of tuples of extra columns to add in the format (colunm_name, column)"""
        # Temporary hack taken from: https://github.com/bradleyayers/django-tables2/issues/70 to avoid the issue where
        # we got the same columns from the previous instance added back
        # Create a copy of base_columns to restore at the end.
        _bc = copy.deepcopy(self.base_columns)
        for col_name, col in extra_cols:
            self.base_columns[col_name] = col
        super(ActivitySummaryTable, self).__init__(*args, **kwargs)
        # restore original base_column to avoid permanent columns.
        type(self).base_columns = _bc

    class Meta:
        attrs = {'class': 'table'}
        order_by = ('activity',)

日付をフィルタリングした後、最後に2つの漂遊日付が追加された例
image

extra_columns引数を使用して817d711で修正されました

このページは役に立ちましたか?
0 / 5 - 0 評価