0

I have two databases in my django application. One is default and another is secondary. When I tried the following code it always returns data from the default database.

from django.db import connection

def my_custom_sql(self):

cursor = connection.cursor()

cursor.execute("SELECT * FROM accounts_account where id=%s", [self.id])

row = cursor.fetchall()

return row

I want to execute the query in second database.

Paulie
  • 6,535
  • 4
  • 20
  • 35
thamshid cc
  • 81
  • 11
  • 4
    Possible duplicate of [Django, multiple databases with raw sql. How to choose db?](https://stackoverflow.com/questions/18223971/django-multiple-databases-with-raw-sql-how-to-choose-db) – ohannes Jul 24 '17 at 19:53
  • Possible duplicate of [Django multiple and dynamic databases](https://stackoverflow.com/questions/6585373/django-multiple-and-dynamic-databases) – emecas Mar 28 '18 at 15:37

1 Answers1

1

you just need to

from django.db import connections

instead of

from django.db import connection

and use your database alias as below:

cursor = connections['secondry_db'].cursor()