Tsubasa ,

  • 5309


  • 0




資料/在 Django 使用多重 Database

  花了一下午練習 Web App 開發,一頭撞上這個問題,找了兩個多小時才找到答案……

  使用版本:Python 2.7、Django 1.8.5


  問題:Can i use different databases for different apps in django?

  敘述:I have multiple apps in my django site. like mainsiteblogtutorials.
     But i want to store different models in different databases so that they can be separated.
     Can i do that in Django?



  Mainsite/ # Project
    AppOne/ #App 1

    AppTwo/ #App 2


  1、首先打開 Mainsite 底下的 settings.py ,將 
DATABASES 的設定修改一下,
    建立需要的 database 設置。
    範例 Code:連結往這邊

  2、在每個 App 資料夾底下建立 dbRouter.py 檔案,Code 及說明見範例。
    範例 Code:連結往這邊

  3、打開 Mainsite 底下的 settings.py ,設定 DATABASE_ROUTERS:

      'AppOne.dbRouter.App1DBRouter', 'AppTwo.dbRouter.App2DBRouter'

    說明及 Code 見範例。
    範例 Code:連結往這邊


  2015-11-20 編輯補充:

  1、在 Django 1.10(dev)下的說明文件:直連/全英文注意。

  2、1.9 開始「syncdb」改為「migrate」,所有的「allow_syncdb」都要修改(見第三點);
    cmd 下的指令分為兩種:
            $ ./manage.py migrate
            $ ./manage.py migrate --database=users


Determine if the migration operation is allowed to run on the database with alias db. Return True if the operation should run, False if it shouldn’t run, or None if the router has no opinion.

The app_label positional argument is the label of the application being migrated.

model_name is set by most migration operations to the value of model._meta.model_name (the lowercased version of the model __name__) of the model being migrated. Its value is None for the RunPython andRunSQL operations unless they provide it using hints.

hints are used by certain operations to communicate additional information to the router.

When model_name is set, hints normally contains the model class under the key 'model'. Note that it may be a historical model, and thus not have any custom attributes, methods, or managers. You should only rely on _meta.

This method can also be used to determine the availability of a model on a given database.

Note that migrations will just silently not perform any operations on a model for which this returnsFalse. This may result in broken foreign keys, extra tables, or missing tables if you change it once you have applied some migrations.