前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django使用多个数据库

django使用多个数据库

作者头像
obaby
发布2023-02-22 10:47:25
4700
发布2023-02-22 10:47:25
举报
文章被收录于专栏:obaby@mars

通过官方文档https://docs.djangoproject.com/zh-hans/3.1/topics/db/multi-db/和csdnhttps://blog.csdn.net/songfreeman/article/details/70229839的这两篇文章可以进行多数据库的设置。但是设置后可能会出现问题,由于我连接的数据库是通过inspactdb的方法得到的model。于是在migrate的时候出现了问题,会提示 1146, “Table xxx doesn’t exist” 。后来发现问题可能出在路由表上,按照DATABASE_APPS_MAPPING映射之后,django默认的表如果要写入可能会找不到数据库。而源代码里的映射关系并不包含新加入的app,例如grappelli等。

代码语言:javascript
复制
DATABASE_APPS_MAPPING = {
# example:
# 'app_name':'database_name',
# 'admin': 'default',
# 'users': 'default', #django
'basic_estate': 'basic_estate',
'footstone': 'footstone',
'mall': 'hsmall',
'iot_biz': 'iot_biz',
'mall': 'mall',
'hsuser': 'hsuser',
}

如果要解决这个问题可以修改router代码,在映射关系内找不到对应的数据库的情况下返回默认数据库连接即可:

代码语言:javascript
复制
# -*- coding: utf-8 -*-
"""
@author: obaby
@license: (C) Copyright 2013-2020, obaby@mars.
@contact: root@obaby.org.cn
@link: http://www.obaby.org.cn
        http://www.h4ck.org.cn
        http://www.findu.co
@file: atabase_router.py.py
@time: 2021/2/26 9:07
@desc:
"""
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 = {'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 'default'

    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 'default'

    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

这样django系统所需的数据库就能正常创建了:

☆文章版权声明☆

* 网站名称:obaby@mars

* 网址:https://h4ck.org.cn/

* 本文标题: 《django使用多个数据库》

* 本文链接:https://h4ck.org.cn/2021/03/django%e4%bd%bf%e7%94%a8%e5%a4%9a%e4%b8%aa%e6%95%b0%e6%8d%ae%e5%ba%93/

* 转载文章请标明文章来源,原文标题以及原文链接。请遵从 《署名-非商业性使用-相同方式共享 2.5 中国大陆 (CC BY-NC-SA 2.5 CN) 》许可协议。


分享文章:

相关文章:

  1. Django admin Foreignkey ManyToMany list_display展示
  2. 再谈《Django 限制访问频率》
  3. Django REST framework foreignkey 序列化
  4. Django 限制访问频率
  5. Opera本地个人数据备份工具
  6. CommentView Plugin for IDAPro7.0
  7. Andoid 图形屏幕锁破解
  8. 获取网页中所有的文字
  9. django 主动抛出 403 异常
  10. django raw_id_fields 显示名称而不是id(raw_id_fields: How to show a name instead of id)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年3月2日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 相关文章:
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档