django raw sql query as dict

Django -- Posted on Feb. 1, 2021

django raw sql query as dict

              
                # 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()
        ]
                  
   
            

Related Posts