我正在使用django框架,我找到了一种方法来存储我通过RPC调用收到的数据。此数据遵循JSON格式:
{"header":["data_enviament","nom_auditor","matricula","bastidor"],"data":[{"data_enviament":"05/1/2014","nom_auditor":"Brutus Brutus, Marc","matricula":"1234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/2/2014","nom_auditor":"Pepito Rudolf, Margarita","matricula":"2234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/5/2014","nom_auditor":"Patrick Linda, Judith","matricula":"5234FRX","bastidor":"192891478kjhda"}],"count":2}
我将这些数据存储到矩阵中(在控制器点),代码为:
for i in range(len(tabla['header'])):
array[0][i] = tabla['header'][i]
x = 1
for data in tabla['data']:
for i in range(len(tabla['header'])):
array[x][i] = data[array[0][i]]
x = x + 1
然后我通过render函数将这些数据解析为模板并表示为html表。 我做得很好还是有其他方法可以做得更好?
答案 0 :(得分:1)
您可以将数据转换为列表列表,按照标题保持项目的顺序。
来自shell的演示:
>>> from django.template import Template, Context
>>> data = {"header":["data_enviament","nom_auditor","matricula","bastidor"],"data":[{"data_enviament":"05/1/2014","nom_auditor":"Brutus Brutus, Marc","matricula":"1234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/2/2014","nom_auditor":"Pepito Rudolf, Margarita","matricula":"2234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/5/2014","nom_auditor":"Patrick Linda, Judith","matricula":"5234FRX","bastidor":"192891478kjhda"}],"count":2}
>>>
>>> data = [[item[header] for header in data['header']] for item in data['data']]
>>> c = Context({'data': data})
>>> template = """
<table>
{% for row in data %}
<tr>
{% for item in row %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
"""
>>> t = Template(template)
>>> print t.render(c)
<table>
<tr>
<td>05/1/2014</td>
<td>Brutus Brutus, Marc</td>
<td>1234FRX</td>
<td>192891478kjhda</td>
</tr>
<tr>
<td>05/2/2014</td>
<td>Pepito Rudolf, Margarita</td>
<td>2234FRX</td>
<td>192891478kjhda</td>
</tr>
<tr>
<td>05/5/2014</td>
<td>Patrick Linda, Judith</td>
<td>5234FRX</td>
<td>192891478kjhda</td>
</tr>
</table>