Reputation: 108
I'm working with the django framework and I found a way to store the data that I recieved by a RPC call. This data follow the JSON format:
{"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}
And I store this data into a matrix( at the controller point ), the code is:
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
Then I parse this data by the render function to the template and represent into a html table. I'm doing fine or there are maybe another way to do it better?
Upvotes: 1
Views: 97
Reputation: 473863
You can transform the data into a list of lists keeping the order of the items according to the header.
Demo from the 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>
Upvotes: 1