2011-07-01 6 views
3

内のすべてのアプリケーションのために個別のデータベースを使用することができ、私はAPP1使用DB1とAPP2使用のDB2をしたいは、どのように私はAPP1とAPP2を持っているジャンゴ

私が見つけたアプローチは、データベースのルータを使用して

少し複雑です

私は何か簡単な方法があることを知りたいですか?

settings.pyで設定することはできますか

+0

私は誰がこれを望むのか分かりません。 –

+0

@ IgnacioVazquez-Abramsこれは、別のデータベースに秘密にしておきたいハッシュキー用の別個のアプリケーションを持っている場合があるためです。 –

答えて

3

いいえ正しい方法はルータを使用することです。それは非常に簡単です。 DjangoのドキュメントのMyAppRouterを参照してください: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 
+0

ありがとう、私はルータのために行くでしょう:D – davyzhang

3

私は正しい答えはここにあると思う:http://diegobz.net/2011/02/10/django-database-router-using-settings。多くのアプリケーションがあり、それぞれに個別のデータベースが必要な場合は、settings.pyに

DATABASE_APPS_MAPPING = {'app1':'db1', 'app2':'db2', 'app3':'db3', 'app4':'db4'} 
DATABASE_ROUTERS += ['DatabaseAppsRouter'] 

を入力してください。

関連する問題