代码之家  ›  专栏  ›  技术社区  ›  Sergey Golovchenko

在Django中运行纯SQL查询时如何获取字段名

  •  6
  • Sergey Golovchenko  · 技术社区  · 17 年前

    在我的一个Django视图中,我使用普通的SQL(而不是ORM)查询数据库并返回结果。

    sql = "select * from foo_bar"
    cursor = connection.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    

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

    3 回复  |  直到 11 年前
        1
  •  9
  •   Ross Rogers    11 年前

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

        2
  •  7
  •   ZAD-Man    11 年前

    Django docs 提供了一个非常简单的方法(它确实使用 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()
        ]
    
        3
  •  3
  •   twasbrillig    11 年前

    我在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""")