Django run sql query to other db

Django -- Posted on Aug. 23, 2024

Django run sql query to other db

              
                from django.db import connections

def dictfetchall(cursor):
    """Return all rows from a cursor as a list of dicts"""
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

def run_raw_query_on_db(db_name,sql_query):
    # Using the cursor to run raw SQL on 'other_db'
    with connections[db_name].cursor() as cursor:
        cursor.execute(sql_query)
        results = dictfetchall(cursor)
    
    return results
                  
   
            

Related Posts