2012-06-04 40 views
12

使用dict_cursor要獲得在Django光標我做的:在Django

from django.db import connection 
cursor = connection.cursor() 

我怎麼會在Django得到一個字典光標,相當於 -

import MySQLdb 
connection = (establish connection) 
dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor) 

有沒有辦法做到這在Django?當我嘗試cursor = connection.cursor(MySQLdb.cursors.DictCursor)時,我得到了Exception Value: cursor() takes exactly 1 argument (2 given)。或者我需要直接連接到python-mysql驅動程序?

Django文檔建議使用dictfetchall

def dictfetchall(cursor): 
    "Returns all rows from a cursor as a dict" 
    desc = cursor.description 
    return [ 
     dict(zip([col[0] for col in desc], row)) 
     for row in cursor.fetchall() 
    ] 

是否有使用這個和創建dict_cursor之間的性能差異?

回答

22

不,沒有這樣的支持在django DictCursor。但是,你可以寫一個小功能,爲你,看到這個ticket

def dictfetchall(cursor): 
    "Returns all rows from a cursor as a dict" 
    desc = cursor.description 
    return [ 
      dict(zip([col[0] for col in desc], row)) 
      for row in cursor.fetchall() 
    ] 

>>> cursor.execute("SELECT id, parent_id from test LIMIT 2"); 
>>> dictfetchall(cursor) 
[{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}] 
0

下面的代碼將結果集到字典中。

from django.db import connections 
cursor = connections['default'].cursor() 

columns = (x.name for x in cursor.description) 
result = cursor.fetchone() 
result = dict(zip(columns, result)) 

如果結果集有多個行,請改爲對光標進行迭代。

columns = [x.name for x in cursor.description] 
for row in cursor: 
    row = dict(zip(columns, row)) 
+0

只是一個有趣的注意。表達式(在cursor.description中x的x.name)產生一個不是列表對象的生成器。這種生成器將在「for cursor in cursor」循環的第一次迭代之後耗盡。爲了使這個代碼示例在多行上工作,我們需要通過將圓括號更改爲方括號來預取列:[x.name,用於cursor.description中的x] –

1

輕鬆與Postgres的做至少,我敢肯定,MySQL有類似(Django的1.11)

from django.db import connections 
from psycopg2.extras import NamedTupleCursor 


def scan_tables(app): 
    conn = connections['default'] 
    conn.ensure_connection() 
    with conn.connection.cursor(cursor_factory=NamedTupleCursor) as cursor: 
     cursor.execute("SELECT table_name, column_name " 
         "FROM information_schema.columns AS c " 
         "WHERE table_name LIKE '{}_%'".format(app)) 
     columns = cursor.fetchall() 
     for column in columns: 
      print(column.table_name, column.column_name) 


scan_tables('django') 

明顯感覺到自由使用DictCursor,RealDictCursor,LoggingCursor等