Django - List of Dictionaries to Tables2

泪湿孤枕 提交于 2019-12-18 09:44:06

问题


afraid I'm a Newbie when it comes to Django.

I have a list of Dictionaries which I want to use to populate a Tables2 table. I don't know how to adapt the list of Dicts to work in Table2 :( The website suggests:

import django_tables2 as tables

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

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

table = NameTable(data)

I can't figure this out! Also, I will be using this view with many different sets of data and so my keys will change over views.

Here's an example of a list of Dictionaries (note that below, the two Dictionaries have the same keys; this always happens in each view; it is just that in different views there will be different sets of keys):

[{'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}]

Would much appreciate anyone's help :)


回答1:


solving my own Q, I found here a way of dynamically making a class at runtime:

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.

and my working code:

 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()
    ]   



回答2:


Create a Table subclass for each type of table you want to display. By type I mean set-of-columns. For example:

import datetime
import django_tables2 as tables

[
    {'trial2_click': u'left', 'timeStored': datetime.time(13, 35, 5), 'runOnWhatHardware': u'bla', 'id': 1L, 'timeStart': datetime.datetime(2012, 11, 2, 12, 54, 58), '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), '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), 'trial1_RT': 234.1, 'approxDurationInSeconds': 123L, 'timeZone': u'UTC', 'expt_id': 4L, 'trial1_click': u'right', 'trial2_RT': 2340L}
]

class TrialTable(tables.Table):
    trial2_click = tables.Column()
    timeStored = tables.TimeColumn()
    runOnWhatHardware = tables.Column()
    timeStart = tables.DateTimeColumn()
    trial1_RT = tables.Column()
    approxDurationInSeconds = tables.Column()
    timeZone = tables.Column()
    expt_id = tables.Column()
    trial1_click = tables.Column()
    trial2_RT = tables.Column()


来源:https://stackoverflow.com/questions/14366098/django-list-of-dictionaries-to-tables2

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