从Django中的原始sql查询中获取关联数组

问题描述 投票:0回答:1

我正在开发Django Web应用程序。我在不使用模型的情况下使用原始sql查询。下面是我到目前为止所拥有的代码。

def getCntlData(self, FID, PID):
        sqlst = 'select * from employee where employeeid = %s'    
        cursor.execute(sqlst, [PID])
        data_row = cursor.fetchall()

        return data_row

我想要的数据采用关联数组的格式或字典的形式,就像PHP在查询mysql时给出的那样。[{“ employeename”:“ Max”,“ employeeage”:“ 34”}]

python mysql django
1个回答
0
投票

摘自preforming raw SQL queries的Django文档

默认情况下,Python DB API将返回不包含其字段的结果名称,这意味着您最终得到的是值列表,而不是字典以较小的性能和内存成本,您可以返回结果通过使用类似这样的命令:

def dictfetchall(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()
    ]
© www.soinside.com 2019 - 2024. All rights reserved.