Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read table data from non-default database in Django?

My django project uses 2 databases, 1 existing database and another one which I am creating through my project using Models. I have defined db's in settings.py as below :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'music': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'myMusicDb.sqlite3'),
    }
}

I generated model data using inspectdb command and everything works fine if I remove the default db from settings.py and make the 'music' db the default db. My query is how to keep both db in settings.py and to work with both DataBases ? Is there any way to tell django to use specific database from settings.py ?

like image 814
Amar Avatar asked Oct 17 '25 19:10

Amar


1 Answers

I found the answer after reading https://docs.djangoproject.com/en/1.7/topics/db/multi-db/. We can either use routers or we can make use of using keyword in query such as -

Album.objects.using('music').all()

Thought to post it, may be it could help someone.

like image 186
Amar Avatar answered Oct 20 '25 09:10

Amar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!