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?

Asked By: David542

||

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")
Answered By: David542

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()
Answered By: Nimit Gupta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.