django同一個項目中鏈接多個數據庫

1、場景與思路

同一個項目中須要鏈接多個數據庫。python

2、代碼

代碼中主要是三個部分,settings、models以及本身寫的一個類。mysql

1.本身寫的文件:database_app_router.py  類名:DatabaseAppsRoutersql

# database_app_router.py
# -*- coding: utf-8 -*-
from django.conf import settings

DATABASE_MAPPING = settings.DATABASES_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
        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

 settings.py文件中修改數據庫

# settings.py

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "integral_wall",
        "USER": "root",
        "PASSWORD": "123456",
        "HOST": "127.0.0.1",
        "PORT": "3306",
    },
    "sdk_51zhuan": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "sdk_51zhuan",
        "USER": "root",
        "PASSWORD": "123456",
        "HOST": "127.0.0.1",
        "PORT": "3306",
    },
}

DATABASES_APPS_MAPPING = {
    'integral_wall': 'default',
    'sdk_db': 'sdk_51zhuan',
'admin': 'sdk_51zhuan',
'auth': 'sdk_51zhuan',
} DATABASE_ROUTERS = ['integral_wall_manager.database_app_router.DatabaseAppsRouter']

 models.py文件修改django

# models.py

class SdkApplication(models.Model):
    """
    應用程序列表
    """
    sdk_type_choices = (
        (0, '不合做'),
        (1, '必定時間內合做'),
        (2, '永久合做'),
    )
    id = models.AutoField(primary_key=True)
    app_id = models.CharField('蘋果商店裏的APP id', max_length=16, default='')
    app_name = models.CharField('應用名稱', max_length=64)
    bundle_id = models.CharField('包ID,域名倒序', max_length=64, default='')
    create_time = models.DateTimeField('建立時間', auto_now_add=True)

    class Meta:
        app_label = 'sdk_db'  # 鏈接的數據庫
        db_table = "sdk_application"  # 表名


class AdRecord(models.Model):
    """
    廣告記錄
    """
    type = models.CharField('操做類型', max_length=16)
    action = models.CharField('操做、行爲', max_length=16)
    create_time = models.DateTimeField('建立時間', auto_now_add=True)

    class Meta:
        # app_label 不寫,使用默認
        db_table = "ad_record"  # 表名

3、執行

執行的順序就是你們熟悉的了:app

1.python manage.py makemigrationsspa

以後的稍有不一樣:code

2.python manage.py migrate --database=sdk_51zhuanrouter

......blog

python manage.py migrate(只有默認數據庫不爲空時才能夠這麼實用,若爲空則是用上面的方法)

其實在這裏沒有特別的執行順序,可是我我的建議你們是最後執行migrate(即默認數據庫)。另外要注意一點,admin、auth是必定要在一個app裏被makemigrations放到一個XXXX_initial.py文件中的,否則你怎麼migrate都不會有這些Django自建的表的!


****最後的最後必定要注意:不在一個庫裏了,無法跨庫創建約束關係,放棄外鍵,老老實實一步步查!****

相關文章
相關標籤/搜索