how to load unstructured non-queryset data with django-tables2

浪子不回头ぞ 提交于 2019-12-13 07:53:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!