django 不使用 orm

本文介绍了一种将数据库查询结果转换为字典的方法,通过定义函数dictfetchall,实现了从游标中获取所有行并将其转换为字典格式。此外,还展示了如何在Django中使用自定义SQL查询更新和检索数据。

def dictfetchall(cursor):
“Returns all rows from a cursor as a dict”
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]

cursor.execute(“SELECT id, parent_id from test LIMIT 2”);
dictfetchall(cursor)
[{‘parent_id’: None, ‘id’: 54360982L}, {‘parent_id’: None, ‘id’: 54360880L}]

from django.db import connection

def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()

    return row
def dictfetchall(cursor):
    "从cursor获取所有行数据转换成一个字典"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值