Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get field names when running plain sql query in django

Tags:

python

django

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?

like image 580
Sergey Golovchenko Avatar asked Apr 30 '09 06:04

Sergey Golovchenko


People also ask

How do you get all field names in a table using SQL query?

USE db_name; DESCRIBE table_name; it'll give you column names with the type.

How can you see raw SQL queries running in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

Does Django ORM support subquery?

¶ Django allows using SQL subqueries.


3 Answers

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()
    ]
like image 111
ZAD-Man Avatar answered Oct 24 '22 20:10

ZAD-Man


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

like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 24 '22 18:10

Ignacio Vazquez-Abrams


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""") 
like image 39
Hey Teacher Avatar answered Oct 24 '22 18:10

Hey Teacher