问题
I'd like to use django-tables2 to display data from a spreadsheet or csv file. The data will always be dynamic so I need a way of dynamically adding columns to my django-tables2 table. From the documentation there seems to be no way of doing this.
Any ideas?
回答1:
In Python, you can use type to construct classes dynamically.
Let's use the example from the docs, which defines a table with one column, name
.
import django_tables2 as tables
data = [
{"name": "Bradley"},
{"name": "Stevie"},
]
class NameTable(tables.Table):
name = tables.Column()
This could be defined dynamically with
NameTable = type('NameTable', (tables.Table,), {'name': tables.Column()})
The data in your spreadsheet will be more complicated, but the same approach should work.
来源:https://stackoverflow.com/questions/31856958/how-to-load-unstructured-non-queryset-data-with-django-tables2