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()
]
from itertools import *
from django.db import connection
def query_to_dicts(query_string, *query_args):
"""Run a simple query and produce a generator
that returns the results as a bunch of dictionaries
with keys for the column values selected.
"""
cursor = connection.cursor()
cursor.execute(query_string, query_args)
col_names = [desc[0] for desc in cursor.description]
while True:
row = cursor.fetchone()
if row is None:
break
row_dict = dict(izip(col_names, row))
yield row_dict
return
示例用法:
row_dicts = query_to_dicts("""select * from table""")
4条答案
按热度按时间7ivaypg91#
在Django文档中,提供了一个非常简单的方法(正如伊格纳西奥所回答的,它确实使用了
cursor.description
)。oknwwptz2#
根据PEP 249,您可以尝试使用
cursor.description
,但这并不完全可靠。7ajki6be3#
我在Doug Hellmann的博客中找到了一个很好的解决方案:
http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html
示例用法:
irlmq6kh4#
请尝试以下代码: