01-修改django默认的数据库
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #连接的数据库名
'PORT': '3306',
'HOST': 'localhost',
'USER': 'root',
'PASSWORD': '123456',
}
}
# 修改项目同名目录下的__init__.py文件
import pymysql
pymysql.install_as_MySQLdb()
02-配置多数据库连接
# Django 要求default 数据库必须定义,但是如果不会用到,其参数字典可以保留为空。若要这样做,你必须为你的所有的应用的模型建立DATABASE_ROUTERS,包括正在使用的contrib 中的应用和第三方应用。
'default': {},
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': '123456',
},
'db02': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db02', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': '123456',
}
}
DATABASE_ROUTERS = ['项目名.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'app01': 'default',
'app02': 'db02',
}
03-实现数据库路由
# 下面我们需要在项目同名目录myproject/myproject下新建一个database_router.py来实现数据库路由
# 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 = {'app01': 'default', 'app02': 'db02'}
"""
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
# 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
04-为每个app的model分别指定所需要连接的数据库
# 编辑app01下的models.py:
class Book(models.Model): #该model使用default数据库
name=models.CharField(max_length=32,primary_key=True,unique=True)
def __str__(self):
return self.name
class Meta:
#app_label = 'app01' #由于该model连接default数据库,所以在此无需指定
ordering = ['name']
db_table = 'book' # 指定生成数据库的表名称
# 编辑app02下的models.py:
class Author(models.Model):
name=models.CharField(max_length=32,primary_key=True,unique=True)
age = models.CharFieid()
def __str__(self):
return self.name
class Meta:
app_label = 'app02' #定义该model的app_label
ordering = ['name']
db_table = 'authoe' # 指定生成数据库的表名称
05-同步数据库
# 同步default节点数据库,只运行不带 --database参数的命令,不对其他数据库进行同步
python manage.py makemigrations
python manage.py migrate
# 同步db02节点数据库:
python manage.py makemigrations
python manage.py migrate --database=db02