Django 后端中立的 DictCursor

5 投票
1 回答
1878 浏览
提问于 2025-04-15 21:51

有没有办法在Django中获取一个与后台无关的字典游标?这个游标应该是字典格式,而不是元组格式。我现在在做一个学校项目,必须使用Oracle。

在Python的MySQLDb模块中,这个游标叫做DictCursor。

在WoLpH的启发下,我知道我离目标很近了……

def dict_cursor(cursor):
    for row in cursor:
        yield dict(zip(cursor.description, row))

以前我遍历并打印每一行游标时,结果是:

(482072, 602592, 1)
(656680, 820855, 2)
(574968, 718712, 4)
(557532, 696918, 3))

但是使用dict_cursor后,我得到的是:

{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 482072, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 1, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 602592}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 656680, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 2, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 820855}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 574968, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 4, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 718712}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 557532, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 3, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 696918}

我只想用键,比如说'NET SPENT'。

经过进一步的调整,这个方法似乎有效:

def dict_cursor(cursor):
    for row in cursor:
        out = {}
        for i,col in enumerate(cursor.description):
            out[col[0]] = row[i]
        yield out

-

{'NET_COLLECTED': 602592, 'NET_SPENT': 482072, 'LOT': 1}
{'NET_COLLECTED': 820855, 'NET_SPENT': 656680, 'LOT': 2}
{'NET_COLLECTED': 718712, 'NET_SPENT': 574968, 'LOT': 4}
{'NET_COLLECTED': 696918, 'NET_SPENT': 557532, 'LOT': 3}

1 个回答

7

你可以用几行代码就写出来了 :)

def dict_cursor(cursor):
    description = [x[0] for x in cursor.description]
    for row in cursor:
        yield dict(zip(description, row))

或者如果你真的想节省空间的话:

simplify_description = lambda cursor: [x[0] for x in cursor.description]
dict_cursor = lambda c, d: dict(zip(d, r) for r in c))

撰写回答