gpt4 book ai didi

Django - Tables2 的字典列表

转载 作者:行者123 更新时间:2023-12-04 05:15:11 25 4
gpt4 key购买 nike

恐怕我是 Django 的新手。

我有一个字典列表,我想用它来填充 Tables2表。我不知道如何调整 Dicts 列表以在 Table2 中工作 :( 该网站建议:

import django_tables2 as tables

data = [
{"name": "Bradley"},
{"name": "Stevie"},
]

class NameTable(tables.Table):
name = tables.Column()

table = NameTable(data)

我想不通!此外,我将使用此 View 处理许多不同的数据集,因此我的 key 会随着 View 而变化。

这是字典列表的示例(请注意,下面两个字典具有相同的键;这总是发生在每个 View 中;只是在不同的 View 中会有不同的键集):
[{'trial2_click': u'left', 'timeStored': datetime.time(13, 35, 5), 'runOnWhatHardware': u'bla', 'id': 1L, 'timeStart': datetime.datetime(2012, 11, 2, 12, 54, 58, tzinfo=<UTC>), 'trial1_RT': 234.1, 'approxDurationInSeconds': 123L, 'timeZone': u'UTC', 'expt_id': 2L, 'trial1_click': u'right', 'trial2_RT': 2340L}, {'trial2_click': u'left', 'timeStored': datetime.time(13, 39, 15), 'runOnWhatHardware': u'bla', 'id': 2L, 'timeStart': datetime.datetime(2012, 11, 2, 12, 54, 58, tzinfo=<UTC>), 'trial1_RT': 234.1, 'approxDurationInSeconds': 123L, 'timeZone': u'UTC', 'expt_id': 2L, 'trial1_click': u'right', 'trial2_RT': 2340L}, {'trial2_click': u'left', 'timeStored': datetime.time(15, 32, 59), 'runOnWhatHardware': u'bla', 'id': 3L, 'timeStart': datetime.datetime(2012, 11, 2, 12, 54, 58, tzinfo=<UTC>), 'trial1_RT': 234.1, 'approxDurationInSeconds': 123L, 'timeZone': u'UTC', 'expt_id': 4L, 'trial1_click': u'right', 'trial2_RT': 2340L}]

非常感谢任何人的帮助:)

最佳答案

解决我自己的问题,我找到了 here一种在运行时动态创建类的方法:

Defining a dynamic model factory The basic principle that allows us to create dynamic classes is the built-in function type(). Instead of the normal syntax to define a class in Python:

class Person(object): name = "Julia" The type() function can be used to create the same class, here is how the class above looks using the type() built-in:

Person = type("Person", (object,), {'name': "Julia"}) Using type() means you can programatically determine the number and names of the attributes that make up the class.



和我的工作代码:
 def getTable(table_name):
cursor = connection.cursor()
try:
cursor.execute("""SELECT * FROM %s,%s;""" %(table_name,'subscription_exptinfo')) # want autoincrement key?
exptData = dictfetchall(cursor)
except Exception, e:
''

attrs = {}
cols=exptData[0]

for item in cols:
attrs[str(item)] = tables.Column()

myTable = type('myTable', (tables.Table,), attrs)

return myTable(exptData)

def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]

关于Django - Tables2 的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com