一.在settings.py添加数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'djangoweb', # 数据库名,先前创建的
'USER': 'root', # 用户名,可以自己创建用户
'PASSWORD': '', # 密码
'HOST': '127.0.0.1', # mysql服务所在的主机ip
'PORT': '3306', # mysql服务端口
},
'zhongwen1': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'zhongwen1.sqlite3'),
}
}
二.与 settings.py 文件一级创建 database_router.py 文件:
#!/usr/bin/env python
# coding:utf8
from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING # 在setting中定义的路由表
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def allow_relation(self, obj1, obj2, **hints):
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):
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_name=None, **hints):
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
三.在 settings.py 中设置数据库的路由规则方法
DATABASE_ROUTERS = ['PrjectName.database_router.DatabaseAppsRouter']
四.在 settings.py 中设置APP对应的数据库路由表
DATABASE_APPS_MAPPING = {
‘zhongwen1’: ‘zhongwen1’,
}
五.创建App model.py 指定数据库
class Meta:
app_label = "zhongwen1"
六.生成数据库
在使用django的 migrate 创建生成表的时候,需要加上 –database 参数,
如果不加则将 未 指定 app_label 的 APP的models中的表创建到default指定的数据库中
python manage.py makemigrations
python manage.py migrate --database=zhongwen1
七.查询
models.User.objects.using(dbname).all()