1
0
mirror of https://github.com/django/django.git synced 2024-12-24 18:16:19 +00:00

[4.2.x] Fixed #34409 -- Doc'd limitation of dictfetchall() and namedtuplefetchall() examples.

Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
Backport of 216eb63883 from main
This commit is contained in:
Jesper Olsson 2023-03-22 19:20:58 +01:00 committed by Mariusz Felisiak
parent d118cbb1ed
commit b0b769769e

View File

@ -323,7 +323,10 @@ small performance and memory cost, you can return results as a ``dict`` by
using something like this::
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
"""
Return all rows from a cursor as a dict.
Assume the column names are unique.
"""
columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
@ -336,11 +339,17 @@ immutable and accessible by field names or indices, which might be useful::
def namedtuplefetchall(cursor):
"Return all rows from a cursor as a namedtuple"
"""
Return all rows from a cursor as a namedtuple.
Assume the column names are unique.
"""
desc = cursor.description
nt_result = namedtuple("Result", [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
The ``dictfetchall()`` and ``namedtuplefetchall()`` examples assume unique
column names, since a cursor cannot distinguish columns from different tables.
Here is an example of the difference between the three:
.. code-block:: pycon