Django后端中性DictCurs

2024-04-20 04:05:43 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在Django中获取后端中立字典游标?这将是一个dict而不是tuple的游标。我被迫将甲骨文用于我正在进行的学校项目。在

在Python的MySQLDb模块中,它被称为DictCursor。在

有了沃尔夫鼓舞人心的建议,我知道我已经很接近了。。在

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

迭代并打印用于产生以下结果的每行光标:

^{pr2}$

但是用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}

我只想让它使用密钥,例如“净支出”。在

在进一步改进之后,这似乎奏效了:

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}

Tags: innumberfornettypeoutcursordict
1条回答
网友
1楼 · 发布于 2024-04-20 04:05:43

你可以写几行:)

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

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

^{pr2}$

相关问题 更多 >