Django models數據庫配置以及多數據庫聯用設置
今天來說說web框架Django怎麽配置使用數據庫,也就是傳說中MVC(Model View Controller)中的M,Model(模型)。
簡單介紹一下Django中的MVC:
模型(model):定義你的數據庫,一般都在models.py文件中。
視圖(view):定義你的HTML等靜態網頁文件相關,也就是那些html、css、js等前端的東西。
控制器(controller):定義你的業務邏輯相關,就是你的主要代碼。
正文開始
首先要在你的Django項目中找到兩個文件:setting.py、models.py
然後保證你的app要註冊到setting裏面喲
找到DATABASES處,該處就是配置數據庫的地方,然後進行設置:
首先如果是才創建的項目,那麽你的DATABASES應該是長這樣的:
Django源生默認使用的自帶數據庫sqlite3。如果你要使用自帶的,那你可以完全不用動這裏的設置,如果你要使用其他的數據庫,更改ENGINE的值即可,比如mysql:django.db.backends.mysql
當我們使用其他數據庫時,必須對其他參數進行設置,不然Django可能連不上你指定的數據庫,我這裏拿mysql來舉例
可以看到,多了一些參數,NAME就是你要使用的數據庫名字(實現要創建好,不然Django找不到),USER就是數據庫登陸賬號,然後依次是密碼,IP,端口。
到這裏setting應該就算是配置完成了,接著打開models.py,進行編輯
最後通過CMD進入到你的Django目錄,執行python manage.py makemigrations
再執行python manage.py migrate
成功ok!撒花
如果要進行多數據庫配置,研究了一番,終於搞通了,確實要復雜一些。不過也不是很復雜,多了兩三個步驟,下面我們一個一個步驟來
首先只需要在DATABASE下繼續添加一個字典即可,例如我添加了一個yq,裏面寫清楚了我這個yq要引用的數據庫
然後就是添加路由器DATABASE_ROUTERS和映射DATABASE_APPS_MAPPING
看到了DATABASE_ROUTERS = [‘Yq_Djago.database_router.DatabaseAppsRouter‘]
所以我們現在要去這個路徑下創建一個database_router.py文件,然後進行如下編輯
from django.conf import settings DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING class DatabaseAppsRouter(object): """ A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {‘app1‘: ‘db1‘, ‘app2‘: ‘db2‘} """ def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None def allow_migrate(self, db, app_label, model=None, **hints): """ Make sure the auth app only appears in the ‘auth_db‘ database. """ if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None
最後再在models.py裏面指定我們的表運用的是哪個數據,繼續拿我自己寫的例子舉例
最後通過CMD進入到你的Django目錄,執行python manage.py makemigrations
然後再創建數據庫yq,執行python manage.py migrate --database=yq(不如不寫--database就是默認創建default裏面的)
打開數據庫查看,大功告成!創建的interface和interface2兩張表都在裏面,撒花!!!
Django models數據庫配置以及多數據庫聯用設置