美文网首页服务器相关
Django rest framework 多数据库联用配置和使

Django rest framework 多数据库联用配置和使

作者: 十万个榴莲饼 | 来源:发表于2019-08-02 14:51 被阅读0次

    在settings中配置多个数据库:

    DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': "主从数据库名称",
                'USER': '用户名',
                'PASSWORD': "你的密码",
                'HOST': "主数据库ip地址",
                'PORT': '3306',
                "OPTIONS":{"init_command":"SET default_storage_engine=INNODB;"}
            },
            'slave': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': "从数据库名称",
                'USER': '用户名',
                'PASSWORD': "你的密码",
                'HOST': "从数据库ip地址",
                'PORT': '3306',
                "OPTIONS":{"init_command":"SET default_storage_engine=INNODB;"}
            }
    
            }
    
    
    DATABASE_ROUTERS = ['project_name.database_router.DatabaseAppsRouter']
    DATABASE_APPS_MAPPING = {
        # example:
        #'app_name':'database_name',
        'app1': 'default',   #主数据库
        'app2': 'slave',   #从数据库
    }
    

    在settings的同级目录下新建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
    

    注意:
    1.配置完成后,终端里的迁移命令变更为:
    app1迁移主数据库:
    ]# python manage.py makemigrations app1
    ]# python manage.py migrate

    app1迁移主数据库:
    ]# python manage.py makemigrations app2
    ]# python manage.py migrate --database=slave

    (如果不是defalut(默认数据库)要在命令后边加 --database=数据库对应的settings.py中的名称 如: --database=db1 或 --database=db2)

    2.数据库orm操作变更:
    查询
    YourModel.objects.using('db1').all()
    或者 YourModel.objects.using('db2').all()

    保存 或 删除
    user_obj.save(using='new_users')
    user_obj.delete(using='legacy_users')

    参考:https://code.ziqiangxuetang.com/django/django-multi-database.html

    相关文章

      网友评论

        本文标题:Django rest framework 多数据库联用配置和使

        本文链接:https://www.haomeiwen.com/subject/ohokdctx.html