Django测试开发-24-Django多数据库联用

为每个数据库设定一个数据库

1. 在setting.py中新增多个数据库,修改DATABASES 

DATABASES = {
    # 第一个数据库

    'default': {
        'ENGINE':'django.db.backends.mysql',# 选择mysql数据库
        'NAME':'my_app',# 数据库的名字
        'USER':'root',# mysql数据库的用户名
        'PASSWORD':'123456',# mysql数据库的密码
        'HOST':'127.0.0.1',# mysql数据库的主机名
        'POST':3306,# mysql数据库的端口号(这个可写可不写)
    },
    # 第二个数据库
    'MyDjango':{
        'ENGINE':'django.db.backends.mysql',# 选择mysql数据库
        'NAME':'mydjango_db',# 数据库的名字
        'USER':'root',# mysql数据库的用户名
        'PASSWORD':'123456',# mysql数据库的密码
        'HOST':'127.0.0.1',# mysql数据库的主机名
        'POST':3306,# mysql数据库的端口号(这个可写可不写)
    }
}

其他类型数据库添加方式:

django.db.backends.postgresql 连接 PostgreSQL
django.db.backends.mysql 连接 mysql
django.db.backends.sqlite3 连接 sqlite
django.db.backends.oracle 连接 oracle

2.在与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

3. 在settings.py中新增DATABASE_ROUTERS 和DATABASE_APPS_MAPPING

# 指定APP对应的数据库
DATABASE_ROUTERS = ['MyDjango.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    # example:
    #'app_name':'database_name',
    'my_app': 'default',
    'develop': 'default',
    'vote': 'default',
}

其中MyDjango为settings.py或者database_router.py所在目录,即项目名称

如果不设置或者没有设置的app就会自动使用默认的(default)数据库

 

posted @ 2020-03-27 15:59  旅行没有终点  阅读(258)  评论(0编辑  收藏  举报