如何动态创建 Tables2 class

How to create the Tables2 class dynamically

在示例目录的 tables.py 中有:

class Bootstrap4Table(tables.Table):
    country = tables.Column(linkify=True)
    continent = tables.Column(accessor="country__continent", linkify=True)
    class Meta:
        model = Person
        template_name = "django_tables2/bootstrap4.html"
        attrs = {"class": "table table-hover"}
        exclude = ("friendly",)

我正在尝试动态创建 table class,所以我做了: 像这样覆盖 get_table 方法:

def get_table(self, **kwargs):
    """
    Return a table object to use. The table has automatic support for
    sorting and pagination.
    """
    table_class, table_data = type('QueryTable', (tables.Table), myTableCol), mylist
    table_class = table_class
    print(table_class, table_data)
    table = table_class(data=table_data, **kwargs)
    return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table)

table_class、table_data 是我创建 class 的地方。 myTableCol 提供列,mylist 提供每列的数据。我的问题是当我动态创建 table class 时,我不知道如何包含 template_name = "django_tables2/bootstrap4.html"。 另外,当我这样做时,tables 不显示任何边框。

我正在从 rdf 图表中提取数据,但我不知道列的名称或数量,所以我想动态创建列以及使用 Meta class 和 template_name = "django_tables2/bootstrap4.html.

我通过 /django_tables2/tables.py.

弄明白了

所以,我首先创建了一个 Meta class 作为我想创建的 class 的内部 class:

Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},})

然后我将此 class 附加到 myTableCol(我需要更改名称)字典,如 myTableCol.update({'Meta':Meta}).

接下来,我创建了我想要的 class:

QueryTable2=type('QueryTable', (tables.Table,), myTableCol)

我必须更新列名字典的原因是 DeclarativeColumnsMetaclassclass 的 /django_tables2/tables.py 中的第 34-39 行循环遍历了属性class 并检查 myTableCol 中的项目是否是列的实例。如果为真,则键和值将附加到字典列表中,否则,它们将作为 key/value 对添加到另一个字典中。

所以,我更新了我的 get_table,比如:

def get_table(self, **kwargs):
    """
    Return a table object to use. The table has automatic support for
    sorting and pagination.
    """
    ....
    other processing
    ....

    Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},})
    myTableCol.update({'Meta':Meta})
    QueryTable2=type('QueryTable', (tables.Table,), myTableCol)
    table_class, table_data =  QueryTable2, mylist
    table_class = table_class
    print(table_class, table_data)
    table = table_class(data=table_data, **kwargs)
    return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table)