zoukankan      html  css  js  c++  java
  • Django之连接多个数据库的相关配置

    01-修改django默认的数据库

    # settings.py
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mysql01', #连接的数据库名
            'PORT': '3306',
            'HOST': 'localhost',
            'USER': 'root',
            'PASSWORD': '123456',
        }
    }
    # 修改项目同名目录下的__init__.py文件
    
    import pymysql
    
    pymysql.install_as_MySQLdb()

    02-配置多数据库连接

    # Django 要求default 数据库必须定义,但是如果不会用到,其参数字典可以保留为空。若要这样做,你必须为你的所有的应用的模型建立DATABASE_ROUTERS,包括正在使用的contrib 中的应用和第三方应用。
    
    'default': {},
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mysql01', #连接的数据库名
            'HOST': 'localhost',
            'PORT': '3306',
            'USER': 'root',
            'PASSWORD': '123456',
        },
        'db02': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'db02', #连接的数据库名
            'HOST': 'localhost',
            'PORT': '3306',
            'USER': 'root',
            'PASSWORD': '123456',
        }
    }
    
    DATABASE_ROUTERS = ['项目名.database_router.DatabaseAppsRouter']
    DATABASE_APPS_MAPPING = {
        'app01': 'default',
        'app02': 'db02',
    }

    03-实现数据库路由

    # 下面我们需要在项目同名目录myproject/myproject下新建一个database_router.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 = {'app01': 'default', 'app02': 'db02'}
        """
    
        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

    04-为每个app的model分别指定所需要连接的数据库

    # 编辑app01下的models.py:
    
    class Book(models.Model): #该model使用default数据库
        name=models.CharField(max_length=32,primary_key=True,unique=True)
        
    
        def __str__(self):
            return self.name
    
        class Meta:
            #app_label = 'app01' #由于该model连接default数据库,所以在此无需指定
            ordering = ['name'] 
            db_table = 'book'  # 指定生成数据库的表名称
    # 编辑app02下的models.py:
    
    class Author(models.Model):
        name=models.CharField(max_length=32,primary_key=True,unique=True)
        age = models.CharFieid()
    
        def __str__(self):
            return self.name
    
        class Meta:
            app_label = 'app02'  #定义该model的app_label
            ordering = ['name'] 
            db_table = 'authoe'  # 指定生成数据库的表名称

    05-同步数据库

    # 同步default节点数据库,只运行不带 --database参数的命令,不对其他数据库进行同步
    
    python manage.py makemigrations
    
    python manage.py migrate
    # 同步db02节点数据库:
    
    python manage.py makemigrations
    
    python manage.py migrate --database=db02
  • 相关阅读:
    设计模式之一 简单工厂模式
    PowerShell_7_零基础自学课程_7_Powershell中重定向机制、目录和文件管理
    PowerShell_2_零基础自学课程_2_Powershell与Cmd以及Unix/Linux Shell
    PowerShell_3_零基础自学课程_3_如何利用Powershell ISE调试PS脚本
    (转)越狱的 iPhone、iPad 通过网站实现一键安装 ipa 格式的 APP 应用
    (转)直接拿来用!最火的Android开源项目(二)
    (转)iOS编程高性能之路-自动化编译脚本(2)
    (转)iOS编程高性能之路-自动化编译脚本(1)
    (转)How to Install Xcode, Homebrew, Git, RVM, Ruby & Rails on Snow Leopard, Lion, and Mountain Lion
    (转)直接拿来用!最火的Android开源项目(一)
  • 原文地址:https://www.cnblogs.com/pgxpython/p/9982848.html
Copyright © 2011-2022 走看看