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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM