summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorJames Bennett <ubernostrum@gmail.com>2011-09-11 05:37:55 +0000
committerJames Bennett <ubernostrum@gmail.com>2011-09-11 05:37:55 +0000
commit23b7758f75a7a676613464cc3f00370979df1e45 (patch)
tree50087aea9668c51080588e8caac8ed19f00a0d64 /docs
parent7b92ae310d59e39f91e9ee4d887c0ea7ae85e4fd (diff)
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
Diffstat (limited to 'docs')
-rw-r--r--docs/topics/db/sql.txt24
1 files changed, 24 insertions, 0 deletions
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt
index 1b1e94654f..9527860f78 100644
--- a/docs/topics/db/sql.txt
+++ b/docs/topics/db/sql.txt
@@ -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