django raw sql query as dict

Django February 01, 2021 python

django raw sql query as dict

python
# it is copy paste from the django documentation 
# the difference is in this function is that  an sql string is passed as parameter instead of cursor

from django.db import connection

def dictfetchall(query):
    "Return data from raw sql query  as a dict"
    with connection.cursor() as cursor:
        cursor.execute(query)
        columns = [col[0] for col in cursor.description]
        return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]