https://www.cnblogs.com/zhansen0924/articles/9476171.html

    一、在settings里面添加一下内容:
    django 不同应用连接不同数据库 - 图1

    二、在和settings同一级目录下新建一个py文件,文件名可以随意取,我这里为database_router.py,代码如下:

    1. from django.conf import settings
    2. database = settings.DATABASES_APPS_MAPPING # 加载到配置文件里面的对应关系的变量
    3. class DatabaseAppRouter(object):
    4. def db_for_read(self, model, **hints): # 对数据库进行读操作时要指向的数据库
    5. if model._meta.app_label in database:
    6. return database[model._meta.app_label]
    7. return None
    8. def db_for_wirte(self, model, **hints): # 对数据库进行写操作时要指向的数据库
    9. if model._meta.app_label in database:
    10. return database[model._meta.app_label]
    11. return None
    12. def db_for_relation(self, obj1, obj2, **hints): # 确保创建的两个模型是指向的同一数据库,然后两个模型可以做关联
    13. db_obj1 = database.get(obj1._meta.app_label)
    14. db_obj2 = database.get(obj2._meta.app_label)
    15. if db_obj1 and db_obj2:
    16. if db_obj1 == db_obj2:
    17. return True
    18. else:
    19. return False
    20. return None
    21. def allow_syncdb(self, db, model): # 允许同步数据到指定的数据库
    22. if db in database.values():
    23. return database.get(model._meta.app_label) == db
    24. elif model._meta.app_label in database:
    25. return False
    26. return None
    27. def allow_migrate(self, db, app_label, model=None, **hints): # 允许将模型转换为sql语句
    28. if db in database.values():
    29. return database.get(app_label) == db
    30. elif app_label in database:
    31. return False
    32. return None

    三、在应用里面创建model时,需要指定数据库:

    django 不同应用连接不同数据库 - 图2

    四、使用manage.py生成数据表的时候,需要加参数:

    python manage.py makemigrations app01 #指定要生成数据表的app
    python manage.py migrate —database=db01 #生成sql时指定对应的数据库名称(不是应用名)

    五、在做增、删、改、查的时候,需要制定对应的数据库:

    django 不同应用连接不同数据库 - 图3

    到此,就OK了!