django 多数据库配置
修改项目的 settings 配置
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'),
},
}
DATABASE_ROUTERS = ['Prject_name.database_router.DatabaseAppsRouter']
# Project: 建立的django项目名称(project_name)
# database_router: 定义路由规则database_router.py 文件名称, 这个文件名可以自己定义
# DatabaseAppsRouter: 路由规则的类名称,这个类是在database_router.py 文件中定义
DATABASE_APPS_MAPPING = {
# 设置APP对应的数据库路由表 ,如果不指定则会自动创建到默认(default)的数据库中
# example:
# 'app_name':'database_name',
'app02': 'db02',
'app01': 'db01',
'admin': 'db01',
'auth': 'db01',
'contenttypes': 'db01',
'sessions': 'db01',
}
创建数据库路由规则
创建 database_router.py 文件,与 settings.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 中配置的数据库名下
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"
生成数据表
在使用django的 migrate 创建生成表的时候,需要加上 –database 参数,如果不加则将 未 指定 app_label 的 APP的models中的表创建到default指定的数据库中,如:
python manage.py migrate --database=db01
以上创建完成后,其它所有的创建、查询、删除等操作就和普通一样操作就可以了,无需再使用类似
models.User.objects.using(dbname).all()
浙公网安备 33010602011771号