django操作多数据库

1、    添加数据库路由分配文件

在项目文件夹里创建‘database_router’文件。将下面的代码复制到该文件里。

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

        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

2、在settings.py文件中配置多数据库

# Database

# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'django_test',

        'HOST': '127.0.0.1',

        'USER': 'root',

        'PASSWORD': '',

        'PORT': '',

},

#配置第二个数据库

    'test': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'xsanjiaocheng',

        'HOST': '127.0.0.1',

        'USER': 'root',

        'PASSWORD': '',

        'PORT': '',

    }

}

#设置数据库路由,将django_test改为你项目的名称。

DATABASE_ROUTERS = ['django_test.database_router.DatabaseAppsRouter']

#配置数据库与app的对应关系

DATABASE_APPS_MAPPING = {

    # example:

    # 'app_name':'database_name',

    # 'app01': 'test',

    'app01': 'default',

    'app02': 'test',

}

3、    在对应的app里的models.py文件里正常创建数据表即可(在创建表时尽量不要使用同样的表名)

app01中的models.py:

class django_test_1(models.Model):

    abc = models.CharField(max_length=20)

    class Meta:

        app_label='app01'

app02中的models.py:

class test_1(models.Model):

    tests= models.CharField(max_length=20)

4、    生成迁移文件

和以前一样:python manage.py makemigrations

5、    迁移数据库

迁移时需指定数据库名

python manage.py migrate  database=test

如果针对已创建好的数据库创建对应的models.py文件不用生成迁移文件,直接执行“python manage.py  inspectdb > app02/models.py  --database=test”的命令即可。

  在django 2.1.1版本中需要执行“python manage.py  inspectdb  --database=test > app02/models.py ”

6、操作数据库

1)手动选择数据库

django_test_1.objects.using('default').create(abc='hdajh')

2)自动选择数据库

和以前一样不加using()。

7、 配置urls.py

导入对应app的views.py的文件。最好命名个别名,或者给views.py文件重命名。

其他使用和以前一样。

django操作多数据库的更多相关文章

  1. Django 操作Mysql数据库

    pip安装mysqlclient sudo ln -s /usr/local/mysql/bin/mysql_config /usr/local/bin/mysql_config sudo pip i ...

  2. django MVC模式 数据库的操作mysql

    介绍:本节课我们继续学习djangoWEB框架的开发,这节课主要是学习如何访问数据库,django如何自动为我们创建好表结构等相关内容. 1.首先我们打开settings.py找到DATABASES关 ...

  3. django之ORM数据库操作

    一.ORM介绍 映射关系: 表名 -------------------->类名 字段-------------------->属性 表记录----------------->类实例 ...

  4. django基础之数据库操作

    Django 自称是“最适合开发有限期的完美WEB框架”.本文参考<Django web开发指南>,快速搭建一个blog 出来,在中间涉及诸多知识点,这里不会详细说明,如果你是第一次接触D ...

  5. django连接mysql数据库以及建表操作

    django连接mysql数据库需要在project同名的目录下面的__init__.py里面加入下面的东西 import pymysql pymysql.install_as_MySQLdb() 找 ...

  6. Django框架----ORM数据库操作

    一.ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说,ORM是通过使用 ...

  7. django 笔记4 数据库操作

    django操作数据库 orm操作 对应关系 models.tb.objects.filter(id__gt=) models.tb.objects.filter(id=) models.tb.obj ...

  8. 关于Django中的数据库操作API之distinct去重的一个误传

    转载自http://www.360doc.com/content/18/0731/18/58287567_774731201.shtml django提供的数据库操作API中的distinct()函数 ...

  9. Django 操作已经存在的数据库

    反向操作数据库 何为反向操作.即是数据库在项目之前已经存在,不需要新建表,操作已经存在的表 # 进入站点目录下执行 python manage.py inspectdb #可以看到settings中连 ...

随机推荐

  1. Dubbo下载-从missing artifactId说起

    项目pom文件引入dubbo 报 missing artifactId https://github.com/dangdangdotcom/dubbox 从GitHub上直接下载解压包, 最好下载分支 ...

  2. 如何去掉iview里面的input,button等一系列标签自带的蓝色边框

    只需要将这些标签加一个:focus{outline:0}即可解决这个问题

  3. 【MUI框架】学习笔记整理 Day 1

    MUI 框架之 [原生UI] (1)accordion(折叠面板) 由二级列表演化而来 <ul class="mui-table-view"> 2 <li cla ...

  4. LeetCode 544----Output Contest Matches

    During the NBA playoffs, we always arrange the rather strong team to play with the rather weak team, ...

  5. How To Improve Deep Learning Performance

    如何提高深度学习性能 20 Tips, Tricks and Techniques That You Can Use ToFight Overfitting and Get Better Genera ...

  6. 分布式文件系统比较出名的有HDFS  和 GFS

    分布式文件系统比较出名的有HDFS  和 GFS,其中HDFS比较简单一点.本文是一篇描述非常简洁易懂的漫画形式讲解HDFS的原理.比一般PPT要通俗易懂很多.不难得的学习资料. 1.三个部分: 客户 ...

  7. Windows远程桌面Debian配置

    由于xrdp.gnome和unity之间的兼容性问题,在Debian仍然无法使用xrdp登陆gnome或unity的远程桌面,现象是登录后只有黑白点为背景,无图标也无法操作.使用xrdp只能登录xfc ...

  8. hibernate的延迟加载和抓取策略

    一,延迟加载 1.实体类延迟加载 通过代理机制完成,由javassist类库实现运行时代理,修改实体类的字节码实现了运行时代理     <class lazy="true|false& ...

  9. 3.Servlet实例

    一.基础实例 1.参照如下例子创建maven web工程: https://www.cnblogs.com/lukelook/p/9187313.html 2.创建一个简单的Servlet 类 pac ...

  10. [翻译] SCRecorder

    SCRecorder https://github.com/rFlex/SCRecorder An easy Vine/Instagram like video and/or audio record ...