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()
]