Ticket #16293: 16293-1.patch

File 16293-1.patch, 1.2 KB (added by Cal Leeming, 13 years ago)
  • docs/topics/db/sql.txt

     
    240240    # Your code here...
    241241    transaction.commit_unless_managed(using='my_db_alias')
    242242
     243By default, the Python DB API will return results without their field names,
     244which means you end up with a ``list`` of values, rather than a ``dict``. At a
     245small cost of performance, you can apply field names to the results by using
     246something 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
     256Here 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
    243267.. _transactions-and-raw-sql:
    244268
    245269Transactions and raw SQL
Back to Top