如何在Django中运行纯SQL查询时获取字段名
在我的一个Django视图中,我使用普通的SQL语句(不是ORM)来查询数据库,并返回结果。
sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
我能顺利获取到数据,但却没有得到列名。我该怎么才能获取到返回结果的字段名呢?
4 个回答
7
我在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
下面是一个使用的例子:
row_dicts = query_to_dicts("""select * from table""")
26
在Django文档中,有一个非常简单的方法可以使用(这个方法确实用到了cursor.description
,正如Ignacio所回答的那样)。
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()
]
15
根据PEP 249的说明,你可以试着使用cursor.description
这个方法,不过它并不是特别可靠。