Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, multiple databases with raw sql. How to choose db?

Tags:

django

I have a Django project that utilizes multiple databases. https://docs.djangoproject.com/en/dev/topics/db/multi-db/

I perform a lot of raw queries like this:

  cursor = connection.cursor()
  cursor.execute("select * from my_table")
  ....
  transaction.commit_unless_managed()

How can I specify which database to use?

like image 313
user984003 Avatar asked Aug 14 '13 05:08

user984003


1 Answers

Refer django docs on executing custom query directly. Specify database in your connection as given below:

from django.db import connections
cursor = connections['db_alias'].cursor()
cursor.execute("select * from my_table")

And then commit using

from django.db import transaction
transaction.commit_unless_managed(using='db_alias')
like image 105
arulmr Avatar answered Sep 18 '22 15:09

arulmr