[Django]-Using dict_cursor in django

51๐Ÿ‘

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}] 
๐Ÿ‘คAamir Rind

11๐Ÿ‘

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

๐Ÿ‘คkert

5๐Ÿ‘

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))
๐Ÿ‘คSandeep

3๐Ÿ‘

The main Purpose of using RealDictCursor is to get data in list of dictionary format.

And the apt solution is this and that too without using django ORM

def fun(request):

from django.db import connections

import json

from psycopg2.extras import  RealDictCursor



con = connections['default']
con.ensure_connection()
cursor= con.connection.cursor(cursor_factory=RealDictCursor)
cursor.execute("select * from Customer")
columns=cursor.fetchall()
columns=json.dumps(columns)

output:

[{โ€ฆ},{โ€ฆ},{โ€ฆโ€ฆ}]

๐Ÿ‘คSai Pavan

Leave a comment