在我的一个django视图中,我使用普通的sql(不是orm)查询数据库并返回结果.
sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)
我得到的数据很好,但不是列名.如何获取返回的结果集的字段名称?
在Django文档中,提供了一个非常简单的方法(确实使用cursor.description,正如Ignacio所回答的那样).
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()
]
Run Code Online (Sandbox Code Playgroud)
小智 5
我在Doug Hellmann的博客中找到了一个不错的解决方案:
http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html
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
Run Code Online (Sandbox Code Playgroud)
用法示例:
row_dicts = query_to_dicts("""select * from table""")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13265 次 |
| 最近记录: |