Django项目连接多个数据库配置
【Django】连接使用多个数据库
本文章向大家介绍【Django】连接使用多个数据库,主要包括【Django】连接使用多个数据库使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
原文: http://106.13.73.98/__/182/
@[toc]
第一步: 配置你要使用的数据库
在 setting.py 配置文件中的 DATABASES 字典中指定。 注意:默认的 default 数据库别名不可删除,如果不使用,可留空 。
# 先定义好数据库别名DB01 = 'db01' # 第一个数据库别名DB02 = 'db02' # 第二个数据库别名DATABASES = { 'default': {}, # 不可删除,留空 {} DB01: { # 第一个数据库 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db01', 'HOST': 'localhost', 'POST': '3306', 'USER': 'u1', 'PASSWORD': 'user@u1', }, DB02: { # 第二个数据库 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db02', 'HOST': 'localhost', 'POST': '3306', 'USER': 'u2', 'PASSWORD': 'user@u2', } }
第二步: 定义数据库路由方法类
使用多个数据库时,最简单的方法就是设置数据库路由方案,以保证对象对原始数据库的“粘性”,默认所有的查询都会返回到 default 数据库中。
------------↓ 数据库路由类方法详述:
db_for_read(model, **hints):应用于读取类型对象的数据库模型,如果数据库提供附加信息会在hints字典中提供,最后如果没有则返回None。
db_for_write(model, **hints):应用于写入类型对象的数据库模型,hints字典提供附加信息,如果没有则返回None。
allow_relation(obj1, obj2, **hints):外键操作,判断两个对象之间是否是应该允许关系,是返回True,否则返回False,如果路由允许返回None。
allow_migrate(db, app_label, model_name=None, **hints):db确定是否允许在具有别名的数据库上运行迁移操作,操作运行返回True,否则返回False,或者返回None,如果路由器没有意见。
位置参数解释:
app_label:正在迁移的应用程序的标签。
model_name:多个迁移操作设置模型的值,如:model._meta.app_label
------------↑
实现数据库路由的具体步骤如下
1.在 settings.py 文件中配置app与数据库匹配路由表,采用字典形式,app名对应数据库别名:
DB01 = 'db01' # 第一个数据库别名DB02 = 'db02' # 第二个数据库别名# 数据库路由表DATABASE_APPS_MAPPING = { 'app1': DB01, 'app2': DB02, }2.在与 setting.py 同级的目录下创建路由表,app应用会根据上面指定的路由选择数据库。
# db_router文件内容如下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注: 这里的 db_for_read 与 db_for_write 方法中的逻辑是根据app进行分库分表的,即不同的app使用不同的数据库。 如果想要读写分离的逻辑,可见文章补充部分。
3.在 settings.py 文件中配置 DATABASE_ROUTERS 来指定路由表:
# 指定数据库路由表DATABASE_ROUTERS = ['blog.db_router.DatabaseAppsRouter']# blog:项目名称# db_router:路由文件名称# DatabaseAppRouter:路由文件中的路由类名称
第三步:指定数据库进行数据迁移
根据检测到的变化,创建新的迁移文件:
python manage.py makemigratins将模型和迁移数据同步到指定的数据:
# 将应用程序下的模型根据路由迁移到对应的数据库中python manage.py migrate --database=db01 python manage.py migrate --database=db02可通过指定 app_label 来指定模型对应的数据库(例如在app1下指定某个模型将迁移到app2对应的数据库)。
class XX(models.Model): # xx... class Meta: app_label = 'app2' # 如果指定,将在app02对应的数据库下创建数据表
第四步:使用指定的数据库来执行操作
配置完第二步骤中的数据库路由后,便可自动实现在某个app下使用某个数据库。例如,在 app1 中对数据库进行操作,将自动使用 db01 数据库;在 app2 中对数据库进行操作,将自动使用 db02 数据库。
当然你也可以手动指定数据库:
使用查询语句时,通过 using(db_alias) 来指定要操作的数据库。
保存时,使用 obj.save(using=db_alias) 来指定要操作的数据库。
如下示例:
from django.conf import settings# 提前定义好的数据库别名DB01 = settings.DB01 # 'db01'Db02 = settings.DB02 # 'db02'# 在 'db01' 数据库中添加数据models.Md1.objects.using(DB01).create(username='u1')# 在 'db02' 数据库中查询数据models.Md1.objects.using(DB02).all()# save方法obj = models.Md1(username='u2')# 保存到 'db01' 数据库obj.save(using=DB01)# 从 'db01' 数据库中删除数据obj.delete(using=DB01)# 清除查询到的数据的主键# obj.pk = None
补充:实现读写分离的路由方法
一主一从方案:
from django.conf import settings# 提前定义好的数据库别名DB01 = settings.DB01 # 'db01'DB02 = settings.DB02 # 'db02'class DatabaseAppsRouter(object): def db_for_read(self, model, **hints): """读操作""" return DB02 # 通过 'db02' 数据库 def db_for_write(self, model, **hints): """写操作""" return DB01 # 通过 'db01' 数据库一主多从方案:
import randomfrom django.conf import settings# 从库列表FOLLOW_DB_LIST = ['db02', 'db03', 'db04']class DatabaseAppsRouter(object): def db_for_read(self, model, **hints): """读操作""" return random.choice(FOLLOW_DB_LIST) def db_for_write(self, model, **hints): """写操作""" return 'db01'当然你也可以不配置路由,直接使用第四步骤中的示例来实现读写分离。
原文: http://106.13.73.98/__/182/
原文地址:https://www.cnblogs.com/gqy02/p/11340061.html
Django作为Python最流行的web开发框架之一,可以方便地进行app分离,受到广大pythoner的喜爱。当我们一个Django项目多个app需要连接不同数据库时,我们该怎么配置呢?本文将以Python3+Django1.11为例,为大家详细讲解Django项目连接多个MySQL数据库的配置步骤,其他数据库也类似。

1、设置数据库连接
Python3中PyMySQL代替了MySQLdb模块,这里需要做一个简单的配置。
(1)用pip3安装PyMySQL模块
pip3 install PyMySQL
(2)在项目同名目录myproject/myproject下的__init__.py添加以下代码
import pymysql pymysql.install_as_MySQLdb()
(3) 修改settings.py中默认的数据库 default
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}
}
至此,默认数据库连接配置完成。
2、多数据库连接配置
第1步已经实现了一个数据库的连接,这个时候Django项目的app都使用的默认数据库mysql01,但是很多情况我们不同的app需要用不同的数据库。
我们需要在setting.py中进行配置。
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
},
'mysql02': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql02', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}
}
DATABASE_ROUTERS = ['myproject.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'app01': 'default',
'app02': 'mysql02',
}
这里配置了一个数据库路由myproject.database_router.DatabaseAppsRouter,然后对指定app指定了数据库,'app01': 'default', 'app02': 'mysql02',。下面我们需要在唉项目同名目录myproject/myproject下新建一个database_router.py来实现数据库路由。
# database_router.pyfrom django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPINGclass 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
# 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
这样我们就实现了不同app使用不同的数据库了,我们可以使用python manage.py migrate --database=mysql02命令来实现数据库同步(创建表)。
作者:橙子丨Sunty
链接:https://www.jianshu.com/p/1d4442b683e6
来源:简书
