Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dict_cursor in django

Tags:

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?

like image 282
David542 Avatar asked Jun 04 '12 21:06

David542


2 Answers

No there is no such support for DictCursor in Django. But you can write a small function to that for you. See docs: Executing custom SQL directly:

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}]  
like image 146
Aamir Rind Avatar answered Sep 21 '22 15:09

Aamir Rind


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

like image 23
kert Avatar answered Sep 25 '22 15:09

kert