参考文档:https://docs.djangoproject.com/en/1.10/topics/db/multi-db/
1.新建一个router文件,如db_router.py,键入以下内容:
# coding=utf-8
from __future__ import (unicode_literals, absolute_import)
yw_models = (
'Employee',
'Department',
)
class DbRouter(object):
"""
A router to control all database operations on models in the
watchlist application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read watchlist models go to yw DB.
"""
if model.__name__ in yw_models:
return 'yw'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write watchlist models go to yw DB.
"""
if model.__name__ in yw_models:
return 'yw'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the watchlist app is involved.
"""
if obj1.__class__.__name__ in yw_models or obj2.__class__.__name__ in yw_models:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if db in yw_models:
return True
return None
2.修改setting.py
DATABASE_ROUTERS = ['Yw.db_router.DbRouter']//DbRouter的路径
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'admin',
'USER': 'root',
'PASSWORD': '12345678',
'HOST':'127.0.0.1',
'PORT':'3306',
},
'yw': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'yw',
'USER': 'root',
'PASSWORD': '12345678',
'HOST':'127.0.0.1',
'PORT':'3306',
},
}