18

In one of my django views I query database using plain sql (not orm) and return results.

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

I am getting the data fine, but not the column names. How can I get the field names of the result set that is returned?

1
  • This is a simplified example to illustrate that the column names are not known beforehand. So after I get the resultset I needed a way to retrieve the names of the columns as well. Commented Apr 30, 2009 at 13:29

3 Answers 3

30

On the Django docs, there's a pretty simple method provided (which does indeed use cursor.description, as Ignacio answered).

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()
    ]
Sign up to request clarification or add additional context in comments.

3 Comments

@DataGreed That's great to hear, thanks for the confirmation!
I have a left outer join. Any idea how to distinguish the table ? right now with this method i get column names as keys. the keys are from two tables. not able to distinguish whether a column is from which table.
I'm afraid it's been too long since I've worked with this for me to be able to say for sure, sorry. I think it would be worth creating a new question for.
16

According to PEP 249, you can try using cursor.description, but this is not entirely reliable.

3 Comments

Why is this not reliable? Works for me. Should I be worried?
@user984003: "Cursor Objects should respond to the following methods and attributes." (emphasis mine)
"Not entirely reliable" is right. I'm getting cursors with None as their description.
7

I have found a nice solution in Doug Hellmann's blog:

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

Example usage:

  row_dicts = query_to_dicts("""select * from table""") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.