[Fixed]-Django, multiple databases with raw sql. How to choose db?

35👍

Refer django docs on executing custom query directly. Specify database in your connection as given below:

from django.db import connections
cursor = connections['db_alias'].cursor()
cursor.execute("select * from my_table")
data = cursor.fetchall()
for row in data:
    print(data)

And then commit using

from django.db import transaction
transaction.commit_unless_managed(using='db_alias')
👤arulmr

0👍

try this may be it should works.

from django.db import connections
cursor = connections[’my_db_name’].cursor()
# Your code here...
transaction.commit_unless_managed(using=’my_db_name’)

Leave a comment