summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDražen Odobašić <dodobas@candela-it.com>2015-08-29 16:54:51 +0200
committerTim Graham <timograham@gmail.com>2015-09-03 13:11:46 -0400
commit5ab65ca5c900557f508f62a260f9ea53d9d93f37 (patch)
treed2d0831b314a5366cc18a41d5faefc1958bc5f43
parent40bf18e70282784c7923a89c0700a83118b81a50 (diff)
Fixed #25326 -- Added namedtuple example for executing custom SQL.
-rw-r--r--docs/topics/db/sql.txt38
1 files changed, 30 insertions, 8 deletions
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt
index 3008bac9b5..999853c5ee 100644
--- a/docs/topics/db/sql.txt
+++ b/docs/topics/db/sql.txt
@@ -275,28 +275,50 @@ alias::
cursor = connections['my_db_alias'].cursor()
# Your code here...
-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::
+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 and memory 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"
+ "Return 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::
+Another option is to use :func:`collections.namedtuple` from the Python
+standard library. A ``namedtuple`` is a tuple-like object that has fields
+accessible by attribute lookup; it's also indexable and iterable. Results are
+immutable and accessible by field names or indices, which might be useful::
+
+ from collections import namedtuple
+
+ def namedtuplefetchall(cursor):
+ "Return all rows from a cursor as a namedtuple"
+ desc = cursor.description
+ nt_result = namedtuple('Result', [col[0] for col in desc])
+ return [nt_result(*row) for row in cursor.fetchall()]
+
+Here is an example of the difference between the three::
>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> cursor.fetchall()
- ((54360982L, None), (54360880L, None))
+ ((54360982, None), (54360880, None))
>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> dictfetchall(cursor)
- [{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
+ [{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]
+
+ >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
+ >>> results = namedtuplefetchall(cursor)
+ >>> results
+ [Result(id=54360982, parent_id=None), Result(id=54360880, parent_id=None)]
+ >>> results[0].id
+ 54360982
+ >>> results[0][0]
+ 54360982
Connections and cursors
-----------------------