django 多数据库

参考文档:https://docs.djangoproject.com/en/1.10/topics/db/multi-db/

1.新建一个router文件,如db_router.py,键入以下内容:

# coding=utf-8
from __future__ import (unicode_literals, absolute_import)

yw_models = (
  'Employee',
  'Department',
)

class DbRouter(object):
    """
    A router to control all database operations on models in the
    watchlist application.
    """

    def db_for_read(self, model, **hints):
        """
        Attempts to read watchlist models go to yw DB.
        """
        if model.__name__ in yw_models:
            return 'yw'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write watchlist models go to yw DB.
        """
        if model.__name__ in yw_models:
            return 'yw'
        return None

      def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the watchlist app is involved.
        """
        if obj1.__class__.__name__ in yw_models or obj2.__class__.__name__ in yw_models:
            return True
        return None
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if db in yw_models:
            return True
        return None

2.修改setting.py

DATABASE_ROUTERS = ['Yw.db_router.DbRouter']//DbRouter的路径
DATABASES = {
    'default': {
       # 'ENGINE': 'django.db.backends.sqlite3',
       # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin',
        'USER': 'root',
        'PASSWORD': '12345678',
        'HOST':'127.0.0.1',
        'PORT':'3306',

    },
    'yw': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'yw',
        'USER': 'root',
        'PASSWORD': '12345678',
        'HOST':'127.0.0.1',
        'PORT':'3306',
    },
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值