python/django将mysql查询结果转换为字典组

python/django将mysql查询结果转换为字典组

 

使用python查询mysql数据库的时候,默认查询结果没有返回表字段名称,不方便使用。为了方便使用一般会选择将查询结果加上字段名称以字典组的方式返回查询结果。

实现如下:

 
def dict_fetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]
 

详细原理参考:https://docs.djangoproject.com/en/2.0/topics/db/sql/#executing-custom-sql-directly

原文地址:https://www.cnblogs.com/xiao-xue-di/p/11840699.html