如何在django中运行普通的sql查询时获取字段名称

Ser*_*nko 10 python django

在我的一个django视图中,我使用普通的sql(不是orm)查询数据库并返回结果.

sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

我得到的数据很好,但不是列名.如何获取返回的结果集的字段名称?

Ign*_*ams 11

根据PEP 249,您可以尝试使用cursor.description,但这并不完全可靠.


ZAD*_*Man 9

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)