22

要在 django 中获取光标,我会这样做:

from django.db import connection
cursor = connection.cursor()

我如何在 django 中获得一个 dict 光标,相当于 -

import MySQLdb
connection = (establish connection)
dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor)

有没有办法在 django 中做到这一点?当我尝试时,cursor = connection.cursor(MySQLdb.cursors.DictCursor)我得到了一个Exception Value: cursor() takes exactly 1 argument (2 given). 还是我需要直接连接python-mysql驱动?

django 文档建议使用dictfetchall

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

使用它和创建 dict_cursor 之间有性能差异吗?

4

4 回答 4

46

不,Django 中没有这样的支持DictCursor。但是你可以为你写一个小函数。请参阅文档:直接执行自定义 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}] 
于 2013-01-12T14:35:14.240 回答
9

至少用 Postgres 轻松完成,我确信 mysql 有类似的(Django 1.11)

from django.db import connections
from psycopg2.extras import NamedTupleCursor


def scan_tables(app):
    conn = connections['default']
    conn.ensure_connection()
    with conn.connection.cursor(cursor_factory=NamedTupleCursor) as cursor:
        cursor.execute("SELECT table_name, column_name "
                       "FROM information_schema.columns AS c "
                       "WHERE table_name LIKE '{}_%'".format(app))
        columns = cursor.fetchall()
        for column in columns:
            print(column.table_name, column.column_name)


scan_tables('django')

显然可以随意使用 DictCursor、RealDictCursor、LoggingCursor 等

于 2018-02-17T18:13:30.407 回答
4

以下代码将结果集转换为字典。

from django.db import connections
cursor = connections['default'].cursor()

columns = (x.name for x in cursor.description)
result = cursor.fetchone()
result = dict(zip(columns, result))

如果结果集有多行,则改为遍历游标。

columns = [x.name for x in cursor.description]
for row in cursor:
    row = dict(zip(columns, row))
于 2015-08-21T14:35:35.690 回答
1

使用 RealDictCursor 的主要目的是获取字典格式列表中的数据。

不使用 django ORM 的恰当解决方案就是这个和那个

def 乐趣(请求):

from django.db import connections

import json

from psycopg2.extras import  RealDictCursor



con = connections['default']
con.ensure_connection()
cursor= con.connection.cursor(cursor_factory=RealDictCursor)
cursor.execute("select * from Customer")
columns=cursor.fetchall()
columns=json.dumps(columns)

输出:

[{...},{...},{......}]

于 2021-10-14T07:31:16.173 回答