可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
To get a cursor in django I do:
from django.db import connection cursor = connection.cursor()
How would I get a dict cursor in django, the equivalent of -
import MySQLdb connection = (establish connection) dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor)
Is there a way to do this in django? When I tried cursor = connection.cursor(MySQLdb.cursors.DictCursor)
I got a Exception Value: cursor() takes exactly 1 argument (2 given)
. Or do I need to connect directly with the python-mysql driver?
The django docs suggest using 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() ]
Is there a performance difference between using this and creating a dict_cursor?
回答1:
No there is no such support for DictCursor
in django. But you can write a small function to that for you, see this 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}]
回答2:
Easily done with Postgres at least, i'm sure mysql has similar ( 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')
Obviously feel free to use DictCursor, RealDictCursor, LoggingCursor etc
回答3:
The following code converts the result set into a dictionary.
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))
If the result set has multiple rows, iterate over the cursor instead.
columns = [x.name for x in cursor.description] for row in cursor: row = dict(zip(columns, row))