在django项目中, 一个工程中存在多个APP应用很常见. 有时候希望不同的APP连接不同的数据库,这个时候需要建立多个数据 库连接。
在 settings.py 中配置需要连接的多个数据库连接
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'sqlite3'),
},
'db01': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db_01'),
},
'db02': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db_02'),
},
}
假设现在我们用到3个数据库,一个default默认库,一个 db01 和 db02
在 settings.py 中配置 DATABASE_ROUTERS
DATABASE_ROUTERS = ['Prject.database_router.DatabaseAppsRouter']
每个APP要连接哪个数据库,需要在做匹配设置,在 settings.py 文件中做如下配置:
DATABASE_APPS_MAPPING = {
# example:
# 'app_name':'database_name',
'app02': 'db02',
'app01': 'db01',
'admin': 'db01',
'auth': 'db01',
'contenttypes': 'db01',
'sessions': 'db01',
}
以上的app01, app02是项目中的 APP名,分别指定到 db01, db02 的数据库。
为了使django自己的表也创建到你自己定义的数据库中,你可以指定 :admin, auth, contenttypes, sessions 到设定的数据库中,如果不指定则会自动创建到默认(default)的数据库中
在项目工程根路径下(与 settings.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 = {'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
在各自的 APP 中创建数据表的models时,必须要指定表的 app_label 名字,如果不指定则会创建到 default 中配置的数据库 名下, 如下: 在app01下创建models
class Users(models.Model):
name = models.CharField(max_length=50)
passwd = models.CharField(max_length=100)
def __str__(self):
return "app01 %s " % self.name
class Meta:
app_label = "app01"
在app02下创建models
class Users(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
age = models.IntegerField()
def __str__(self):
return "app02 %s" % self.username
class Meta:
app_label = "app02"
class Book(models.Model):
user = models.ForeignKey("Users", on_delete=models.CASCADE)
bookname = models.CharField(max_length=100)
def __str__(self):
return "%s: %s" % (self.user.username, self.bookname)
class Meta:
app_label = "app02"
在 app03创建models 未指定 app_label,创建到default下
class Users(models.Model):
username = models.CharField(max_length=100)
在使用django的 migrate 创建生成表的时候,需要加上 –database 参数,如果不加则将 未 指定 app_label 的 APP的models中 的表创建到default指定的数据库中,如: 将app01下models中的表创建到db01的数据库”db_01”中
./ manage.py migrate --database=db01
将app02下models中的表创建到db02的数据库”db_02”中
./ manage.py migrate --database=db02
将app03下models中的表创建到default的数据库”sqlite3”中
./ manage.py migrate
以上创建完成后,其它所有的创建、查询、删除等操作就和普通一样操作就可以了,无需再使用类似这样的操作
models.User.objects.using(dbname).all()
完整案例如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test1',
'USER': 'root',
'PASSWORD': '12345',
'HOST': '127.0.0.1',
'PORT': '3306'
},
'local': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test2',
'USER': 'root',
'PASSWORD': '12345',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
# projectname换成你自己的项目名啊!!!
DATABASE_ROUTERS = [projectname.database_router.DatabaseAppsRouter]
DATABASES_APPS_MAPPING = {
# 格式是{appname:对应的DATABASES.key}
# 哪个app对应哪个数据库
'appname1': 'default',
'appname2': 'local',
# 这四个最好加上,而且就在一个库里
'admin': 'default',
'auth': 'default',
'contenttypes': 'default',
'sessions': 'default',
}
# coding: utf-8
from django.conf import settings
DATABASE_MAPPING = settings.DATABASES_APPS_MAPPING
class DatabaseAppsRouter():
"""
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
else:
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."""
"""确保身份验证应用程序只出现在“authdb”数据库中。"""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
from django.db import models
# Create your models here.
class Infor(models.Model):
name = models.CharField(max_length=128)
path = models.CharField(max_length=128)
class Meta:
#添加即可,
app_label='appname2'
执行python3 manage.py migrate
的时候先执行除default之外的库,python3 manage.py migrate --database=‘local’