zoukankan      html  css  js  c++  java
  • 关于django操作orm的一些事--反向生成orm、连接多个数据库

    1. django反向生成orm的类代码

    使用命令python manage.py inspectdb > app01/models.py,注意,我这里的app01是app的名字。

    2.django连接多个数据库

    在很多情况下,一个项目里面不止一个app,也不止使用一个库,那么就面临着连接多个数据库的问题。

    那么先来说说,如何连接使用多个app连接多个数据库:

    以mysql为例:

    在settings.py文件里面:

    DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.mysql',
           'NAME': "db0",
           'USER': 'root',
           'PASSWORD': '123456',
           'HOST': '127.0.0.1',
           'PORT': '3306',
      },
       'db1': {
           'ENGINE': 'django.db.backends.mysql',
           'NAME': 'db1',
           'USER': 'root',
           'PASSWORD': '123456',
           'HOST': '127.0.0.1',
           'PORT': '3306',
      },
       'db2': {
           'ENGINE': 'django.db.backends.mysql',
           'NAME': 'db2',
           'USER': 'root',
           'PASSWORD': '123456',
           'HOST': '127.0.0.1',
           'PORT': '3306',
      },
    }
    # 此配置,列表里写:   项目工程的名字.database_router.DatabaseAppsRouter
    DATABASE_ROUTERS = ['your_project_name.database_router.DatabaseAppsRouter']
    DATABASE_APPS_MAPPING = {
       # 这里面对应的是,app的名字和数据库的名字(在上面注册的)
       'app01': 'default',
       'app02': 'db1',
       'app03': 'db2',
    }

    另外,为了能够访问到不同的库,还需要加一个文件,写上数据库的路由:

    你的项目名/项目名的文件夹下(举例:比如我起了一个项目叫test_django,那么在test_django/test_django,也就是和settings.py同级目录),新建一个文件叫:

    database_router.py,写入如下代码:

    # database_router.py
    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

       # for Django 1.4 - Django 1.6
       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

       # Django 1.7 - Django 1.11
       def allow_migrate(self, db, app_label, model_name=None, **hints):
           print(db, app_label, model_name, hints)
           if db in DATABASE_MAPPING.values():
               return DATABASE_MAPPING.get(app_label) == db
           elif app_label in DATABASE_MAPPING:
               return False
           return None

    那么,此时,你就可以访问不同的数据库了。

    3.django多个数据库反向生成orm代码

    现在,多个库已经有了,那么,如何使用不同的库,在不同的app里面生成orm的代码呢?

    python manage.py inspectdb --database db1 > app01/models.py

    注意,上面的db1是你注册在settings.py文件下面的DATABASES,里面的数据库名字,app01是你的app名字。

     

    解决bug:

    当遇到bug:

    # The error was: (1, "Can't create/write to file '/tmp/#sql_7d33_0.MYI' (Errcode: 13 - Permission denied)")
    # Unable to inspect table 'session'

    到数据库所在的服务器上:

    chmod 777 /tmp

    即可解决此问题。

  • 相关阅读:
    Linux系统启动过程
    Window磁盘错误修复chkdsk
    迅雷精简版-纪念走过的时光
    NTP国内时钟服务器
    完完全全彻底删除VMware_Workstation
    Linux默认日志含义
    java 生成泛型的参数的实例 T t=new T()
    dubbo源码解析-zookeeper创建节点
    dubbo服务端,dubbo客户端,注册中心(zk)之间的心跳
    Dubbo阅读笔记——高级功能
  • 原文地址:https://www.cnblogs.com/haiguixiansheng/p/11732162.html
Copyright © 2011-2022 走看看