django2.2连接多个数据库

  作者:记性不好的阁主

参考:https://blog.csdn.net/weixin_45810706/article/details/108344752


1.在settings.py里配置你需要连的数据库


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test1',
        'USER': 'root',
        'PASSWORD': '12345',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    },
    'local': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test2',
        'USER': 'root',
        'PASSWORD': '12345',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    }
  }

# projectname换成你自己的项目名啊!!!
DATABASE_ROUTERS = [projectname.database_router.DatabaseAppsRouter]

DATABASES_APPS_MAPPING = {
    # 格式是{appname:对应的DATABASES.key}
    # 哪个app对应哪个数据库
    'appname1': 'default',
    'appname2': 'local',
    # 这四个最好加上,而且就在一个库里
    'admin': 'default',
    'auth': 'default',
    'contenttypes': 'default',
    'sessions': 'default',
}
2.settings同级目录下创建database_router.py文件,直接粘贴下面代码即可


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

DATABASE_MAPPING = settings.DATABASES_APPS_MAPPING

class DatabaseAppsRouter():
    """
       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
3.在model中加两行,在app_label项添加你想添加的库所对应的appname,如果是想指定的库是default,那写不写app_label都行了,不写就默认到default

from django.db import models

# Create your models here.
class Infor(models.Model):

	name = models.CharField(max_length=128)
    path = models.CharField(max_length=128)
    
    class Meta:
        #添加即可,
        app_label='appname2'
4.正常执行python manage.py makemigrations

5.执行对应数据库迁移python manage.py migrate --database=local


————————————————


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

                        

原文链接:https://blog.csdn.net/weixin_45810706/article/details/108344752



相关推荐

评论 抢沙发

表情

分类选择