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 等级

相关问题

brianmay picture brianmay  ·  6评论

applegrew picture applegrew  ·  17评论

foldedpaper picture foldedpaper  ·  6评论

mpasternak picture mpasternak  ·  9评论

wtfrank picture wtfrank  ·  32评论