I have app1 and app2, I wanna app1 use db1 and app2 use db2
the approach I found is to using database router, a little bit complicated
I wanna know is there any simple way?
Can I just config it in settings.py
I have app1 and app2, I wanna app1 use db1 and app2 use db2
the approach I found is to using database router, a little bit complicated
I wanna know is there any simple way?
Can I just config it in settings.py
No. The correct way is to use routers. It is very simple. See MyAppRouter in django's documentation: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#an-example:
class MyAppRouter(object):
"""A router to control all database operations on models in
the myapp application"""
def db_for_read(self, model, **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'myapp':
return 'other'
return None
def db_for_write(self, model, **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'myapp':
return 'other'
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in myapp is involved"
if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
return True
return None
def allow_syncdb(self, db, model):
"Make sure the myapp app only appears on the 'other' db"
if db == 'other':
return model._meta.app_label == 'myapp'
elif model._meta.app_label == 'myapp':
return False
return None
I think the right answer is here: http://diegobz.net/2011/02/10/django-database-router-using-settings. If you have many applications and want a separate database for each, you put
DATABASE_APPS_MAPPING = {'app1':'db1', 'app2':'db2', 'app3':'db3', 'app4':'db4'}
DATABASE_ROUTERS += ['DatabaseAppsRouter']
into settings.py.