2010-04-20 23 views
5

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} 
+0

我修改了我的光標,我誤解了它的描述對象:) – Wolph 2010-04-21 00:35:32

回答

6

你可以在一對夫婦行:)

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

那個單行不行的B/C你已經失去了你的yield語句,而且我也沒有看到你如何屈服一行,因爲收益不能列表的一部分.. – 2010-04-21 00:06:54

+2

你是完全正確的,我已經修改它:) – Wolph 2010-04-21 00:33:50

+1

當這樣做像日期這樣的列它像datetime.date(2010,10,21)而不是返回一個實際的日期對象。我試圖將自定義SQL結果集作爲JSON返回給我的瀏覽器。 – mikec 2010-10-21 17:33:21