gpt4 book ai didi

python - Django 后端中立的 DictCursor

转载 作者:太空狗 更新时间:2023-10-30 01:03:59 24 4
gpt4 key购买 nike

有什么方法可以在 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}

我只希望它使用 key ,例如“净支出”。

再完善一点之后,这似乎可行:

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}

最佳答案

你可以写成几行:)

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

关于python - Django 后端中立的 DictCursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2678991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com