How to pass 'using' DB to the django connection object
Question:
To query a specific database in django I can do:
Item.objects.using('specific_db').all()
Is there a way to do the same using a django connection? For example:
>>> from django.db import connection
>>> cursor=connection.using('specific_db').cursor()
If not, how could I get a cursor/connection for a specific DB without manually providing all the credentials?
Answers:
According the the django documentation on Using raw SQL on multiple databases, you would use connections
rather than connection
:
from django.db import connections
cursor = connections['specific_db'].cursor()
cursor.execute("select * from item")
Use this code snippet for performing raw SQL queries
from django.db import connection
def connect_to_db():
with connection.cursor() as cursor:
cursor.execute("""SELECT * FROM Table""")
return dict(zip([col[0] for col in cursor.description], row)) for row /
in cursor.fetchall()
To query a specific database in django I can do:
Item.objects.using('specific_db').all()
Is there a way to do the same using a django connection? For example:
>>> from django.db import connection
>>> cursor=connection.using('specific_db').cursor()
If not, how could I get a cursor/connection for a specific DB without manually providing all the credentials?
According the the django documentation on Using raw SQL on multiple databases, you would use connections
rather than connection
:
from django.db import connections
cursor = connections['specific_db'].cursor()
cursor.execute("select * from item")
Use this code snippet for performing raw SQL queries
from django.db import connection
def connect_to_db():
with connection.cursor() as cursor:
cursor.execute("""SELECT * FROM Table""")
return dict(zip([col[0] for col in cursor.description], row)) for row /
in cursor.fetchall()