2

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?

2 Answers 2

12

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")
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I was going to answer in a few. :) Good luck on your project.
shouldn't the connection and cursor to be closed after use for safety ?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.