Reputation: 3
I would like to clear a question, I can currently work with django rest framework linked to a database, would it be possible for me to use 2 databases in the same project (rest framework) to better visualize the databases, without having to create multiple projects? I'm currently testing on msql but the goal later is to migrate to oracle
Upvotes: 0
Views: 57
Reputation: 26
If you have two or more databases in one project, you can specify database routers for each app
settings.py DATABASES
:
DATABASES = {
'default': {
'NAME': 'default_db',
'ENGINE': 'django.db.backends.postgresql',
'USER': 'root',
'PASSWORD': '********'
},
'secondary_db_name': {
'NAME': 'secondary_db',
'ENGINE': 'django.db.backends.mysql',
'USER': 'root',
'PASSWORD': '********'
}
}
app1/router.py
class App1Router:
app_name = "app1"
db_name = "secondary_db_name"
def db_for_read(self, model, **hints):
if model._meta.app_label == app_name:
return db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == app_name:
return db_name
return None
def allow_relation(self, obj1, obj2, **hints):
if (
obj1._meta.app_label == app_name or
obj2._meta.app_label == app_name
):
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == app_name:
return db == db_name
return None
Same file for the second app, but with different app_name
and db_name
. After you created all the routers for all your applications, you should specify them in your settings.py
:
DATABASE_ROUTERS = ['app1.router.App1Router', 'app2.router.App2Router']
If something is unclear, here's the Django Docs
Upvotes: 1