在django文档(https://docs.djangoproject.com/el/2.1/topics/db/sql/)中,我使用的是函数:
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
与
^{pr2}$在控制台中尝试:
testen = my_custom_sql(Ausgaben,"SELECT TYP, count(*) Anzahl, sum(Summe) Summe FROM hhdata_Ausgaben group by typ")
testen
[{'Typ': 'Drogerie', 'Anzahl': 1, 'Summe': 6.0}, {'Typ': 'Essengehen', 'Anzahl': 1, 'Summe': 4.0}, {'Typ': 'Lieferant', 'Anzahl': 1, 'Summe': 50.0}, {'Typ': 'Taschengeld', 'Anzahl': 1, 'Summe': 5.0}]
type(testen)
<class 'list'>
结果看起来像字典,但它是一个列表,我无法访问模板中的键和值:
{% for key,value in testen.items %}
<li><a href="{{key}}">{{value}}</a></li>
{% endfor %}
我做错什么了?在
结果是一个字典列表,列表中的每个字典表示数据库中的一行。因此,循环应该遍历一个列表:
请记住,根据所使用的Python版本的不同,每个字典中键的顺序可能不同。在
相关问题 更多 >
编程相关推荐