Skip to content

Commit

Permalink
Fixed #16293: Document a way to return dicts with column names from a…
Browse files Browse the repository at this point in the history
… DB cursor.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16808 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
ubernostrum committed Sep 11, 2011
1 parent 7b92ae3 commit 23b7758
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions docs/topics/db/sql.txt
Expand Up @@ -240,6 +240,30 @@ alias::
# Your code here...
transaction.commit_unless_managed(using='my_db_alias')

By default, the Python DB API will return results without their field
names, which means you end up with a ``list`` of values, rather than a
``dict``. At a small performance cost, you can return results as a
``dict`` by using something like this::

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()
]

Here is an example of the difference between the two::

>>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
>>> cursor.fetchall()
((54360982L, None), (54360880L, None))

>>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
>>> dictfetchall(cursor)
[{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]


.. _transactions-and-raw-sql:

Transactions and raw SQL
Expand Down

2 comments on commit 23b7758

@gunslinger
Copy link

@gunslinger gunslinger commented on 23b7758 Sep 19, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is should be added on the django db class.

@Surgo
Copy link
Contributor

@Surgo Surgo commented on 23b7758 Feb 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

; not needed

Please sign in to comment.