14

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?

3
  • Have you tried transaction.commit_unless_managed(using = 'database_entry')? Commented Aug 14, 2013 at 5:49
  • Nobody has linked to the actual documentation, which is very clear: docs.djangoproject.com/en/dev/topics/db/transactions Commented Aug 14, 2013 at 5:56
  • the accepted solution worked for me, and then I ran into issues with breaking unit tests... this fixed the issue, but ran quite slowly docs.djangoproject.com/en/4.2/topics/testing/advanced/…… (I ultimately ended up using app config to specify which database to use per env) Commented Sep 5, 2023 at 18:03

2 Answers 2

36

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") data = cursor.fetchall() for row in data: print(data) 

And then commit using

from django.db import transaction transaction.commit_unless_managed(using='db_alias') 
Sign up to request clarification or add additional context in comments.

2 Comments

This answer is incomplete. It doesn't shown an example of at least one SQL query with the cursor, how the transaction will work, and from where did you got that transaction object. @arulmr
module 'django.db.transaction' has no attribute 'commit_unless_managed' apparently removed in 1.8, quite some time ago.
0

try this may be it should works.

from django.db import connections cursor = connections[’my_db_name’].cursor() # Your code here... transaction.commit_unless_managed(using=’my_db_name’) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.