2011-07-01 59 views
3

每一個應用程序,我有APP1和APP2,我想APP1使用DB1和App2使用DB2我怎麼可以使用不同的數據庫在Django

我發現的方法是使用數據庫路由器,有點複雜

我想知道有沒有簡單的方法?

我可以只配置它settings.py

+0

我無法理解爲什麼要這樣做。 –

+0

@ IgnacioVazquez-Abrams有人會想要這樣做,因爲當你有一個單獨的應用程序散列鍵,你想在一個單獨的數據庫,以保持私人 –

回答

3

號正確的方法是使用路由器。這很簡單。見MyAppRouter Django的文檔: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。如果您有多個應用程序並且想爲每個應用程序分別創建一個數據庫,那麼可以將

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

轉換爲settings.py。

相關問題