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
- [Django]-How to setup SSL on a local django server to test a facebook app?
- [Django]-Add a custom permission to a User
- [Django]-Django templates: overriding blocks of included children templates through an extended template
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
- [Django]-How to get OR permissions instead of AND in REST framework
- [Django]-Django REST Framework serializer field required=false
- [Django]-What is "load url from future" in Django
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
- [Django]-How to seed Django project ? โ insert a bunch of data into the project for initialization
- [Django]-Whats the difference between using {{STATIC_URL}} and {% static %}
- [Django]-Django : DRF Token based Authentication VS JSON Web Token
Source:stackexchange.com