(Django DOCSから直接コーディング:https ://docs.djangoproject.com/en/dev/topics/db/multi-db/#automatic-database-routing
ルーターは、データを取得または設定するデータベースを処理します。
アプリケーション用のルーター(「myapp」という名前)が必要な場合
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
settings.pyに次の行を追加することにより、すべての「myapp」アプリケーションデータが独自のデータベース(「other」という名前)で作成/保存/処理されます。残りのすべてのアプリケーションは、デフォルトのデータベースを使用します。
DATABASE_ROUTERS = ['path.to.MyAppRouter']
ルーターはどこにでも保存できます。settings.DATABASE_ROUTERSのパスを修正するだけです。