Using dict_cursor in django

匿名 (未验证) 提交于 2019-12-03 02:51:02

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!