1
0
mirror of https://github.com/django/django.git synced 2024-12-23 01:25:58 +00:00

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

Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
This commit is contained in:
Jesper Olsson 2023-03-22 19:20:58 +01:00 committed by GitHub
parent b00046d2c2
commit 216eb63883
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -323,7 +323,10 @@ small performance and memory cost, you can return results as a ``dict`` by
using something like this:: using something like this::
def dictfetchall(cursor): 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] columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()] 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): 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 desc = cursor.description
nt_result = namedtuple("Result", [col[0] for col in desc]) nt_result = namedtuple("Result", [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()] 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: Here is an example of the difference between the three:
.. code-block:: pycon .. code-block:: pycon