Django有沒有辦法讓後端中立的字典遊標?這將是一個字典,而不是一個元組。我被迫將Oracle用於我正在開展的學校項目。Django後端中立DictCursor
在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}
我修改了我的光標,我誤解了它的描述對象:) – Wolph 2010-04-21 00:35:32