Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #16293: Document a way to return dicts with column names from a…

… DB cursor.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16808 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 23b7758f75a7a676613464cc3f00370979df1e45 1 parent 7b92ae3
James Bennett authored September 11, 2011

Showing 1 changed file with 24 additions and 0 deletions. Show diff stats Hide diff stats

  1. 24  docs/topics/db/sql.txt
24  docs/topics/db/sql.txt
@@ -240,6 +240,30 @@ alias::
240 240
     # Your code here...
241 241
     transaction.commit_unless_managed(using='my_db_alias')
242 242
 
  243
+By default, the Python DB API will return results without their field
  244
+names, which means you end up with a ``list`` of values, rather than a
  245
+``dict``. At a small performance cost, you can return results as a
  246
+``dict`` by using something like this::
  247
+    
  248
+    def dictfetchall(cursor):
  249
+        "Returns all rows from a cursor as a dict"
  250
+        desc = cursor.description
  251
+        return [
  252
+            dict(zip([col[0] for col in desc], row))
  253
+            for row in cursor.fetchall()
  254
+        ]
  255
+
  256
+Here is an example of the difference between the two::
  257
+
  258
+    >>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
  259
+    >>> cursor.fetchall()
  260
+    ((54360982L, None), (54360880L, None))
  261
+    
  262
+    >>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
  263
+    >>> dictfetchall(cursor)
  264
+    [{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
  265
+
  266
+
243 267
 .. _transactions-and-raw-sql:
244 268
 
245 269
 Transactions and raw SQL

0 notes on commit 23b7758

Please sign in to comment.
Something went wrong with that request. Please try again.