thamshid cc
thamshid cc

Reputation: 81

How to select database in django db collection custom query?

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.

Upvotes: 0

Views: 1919

Answers (1)

MohammadHossein.Sh
MohammadHossein.Sh

Reputation: 50

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

Upvotes: 1

Related Questions