首先,在settings配置上另一个数据库running
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'running': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'running',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
接着往项目中同步表inspectdb (‘> models.py’指定创建到根目录下的文件中,前面也可以加想要的表的名字)
python manage.py inspectdb —database=running —settings=settings.local > models.py
然后去创建一个APP用来存放他,记得在settings中注册running
django-admin startapp running
然后把刚刚的models.py的内容搬到running中去
同时,也得在admin.py中注册models
from django.contrib import admin
# Register your models here.
from myyuque.running.models import Country, Province
admin.site.register(Country)
admin.site.register(Province)
接着重点来了!
需要配置数据库路由,base.py同目录下创建router.py
# -*- coding: utf-8 -*-
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 'default'
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 'default'
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
# for Django 1.4 - Django 1.6
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
# Django 1.7 - Django 1.11
def allow_migrate(self, db, app_label, model_name=None, **hints):
# print db, app_label, model_name, hints
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
然后在base.py 中配置
# 配置多数据库路由
DATABASE_ROUTERS = ['settings.router.DatabaseAppsRouter'] # 路径
# 根据app名称路由指定的数据库
DATABASE_APPS_MAPPING = {
'running': 'running',
}
最后在running的models.py中的每个Meta加上 app_label = ‘running’