在我的一个django视图中,我使用普通sql(而不是orm)查询数据库并返回结果。如何在django中运行纯sql查询时获取字段名称
sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
我得到的数据很好,但没有列名。我如何获得返回的结果集的字段名称?
在我的一个django视图中,我使用普通sql(而不是orm)查询数据库并返回结果。如何在django中运行纯sql查询时获取字段名称
sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
我得到的数据很好,但没有列名。我如何获得返回的结果集的字段名称?
根据PEP 249,您可以尝试使用cursor.description
,但这并不完全可靠。
谢谢,这正是我所需要的。 – 2009-04-30 07:37:32
为什么这不可靠?适用于我。我应该担心吗? – user984003 2013-01-10 18:31:22
@ user984003:“游标对象**应该对以下方法和属性作出响应。” (强调我的) – 2013-01-10 19:09:13
我发现在道格·海尔曼的博客一个很好的解决方案:
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""")
在Django docs,有提供了一个非常简单的方法(不正如Ignacio回答的那样,确实使用cursor.description
)。
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()
]
为什么地球上你需要这种东西?这听起来像是一个等待发生的错误。 – 2009-04-30 10:24:01
这是一个简化的例子,用于说明列名不是事先知道的。所以在得到结果集之后,我需要一种方法来检索列的名称。 – 2009-04-30 13:29:02