Author: ubernostrum Date: 2011-09-10 22:38:50 -0700 (Sat, 10 Sep 2011) New Revision: 16809
Modified: django/branches/releases/1.3.X/docs/topics/db/sql.txt Log: [1.3.X] Fixed #16293: Document a way to return dicts with column names from a DB cursor. Backport of [16808] from trunk. Modified: django/branches/releases/1.3.X/docs/topics/db/sql.txt =================================================================== --- django/branches/releases/1.3.X/docs/topics/db/sql.txt 2011-09-11 05:37:55 UTC (rev 16808) +++ django/branches/releases/1.3.X/docs/topics/db/sql.txt 2011-09-11 05:38:50 UTC (rev 16809) @@ -236,6 +236,30 @@ # 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 -- You received this message because you are subscribed to the Google Groups "Django updates" group. To post to this group, send email to django-updates@googlegroups.com. To unsubscribe from this group, send email to django-updates+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-updates?hl=en.