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

即可解决此问题。

最新文章

  1. chrome中hack解决input:-webkit-autofill自定义样式
  2. Server Transfer()和Response.Redirect()的使用
  3. UVA_393_Doors_(计算几何基础+最短路)
  4. gridView 布局间距合理化的有效办法
  5. python学习之路-5 基础进阶篇
  6. FZUOJ Problem 2178 礼品配送
  7. SQL Server 连接问题-命名管道
  8. Selenium自动化-调用Mysql数据库
  9. vue-cli的跨域配置(自己总结)
  10. 编译openwrt时报错:g++: internal compiler error: Killed (program cc1plus)
  11. webpack之牛刀小试 打包并压缩html、js
  12. jQuery 位置
  13. js 实现List
  14. You are using pip version 9.0.1, however version 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command.
  15. web前端----Bootstrap框架
  16. Entities、pads、links 实体、垫、链接
  17. Ubuntu-18.04Python2与Python3自由切换
  18. APP 渠道推广【摘自网络】
  19. windows7开机后,罗技k380无法自动连接解决办法
  20. light table 添加行号 更新

热门文章

  1. Markdown 打出上下标
  2. Linux下WebLogic的启动、停止和后台运行的方法
  3. 安装关系型数据库MySQL 安装大数据处理框架Hadoop
  4. Remind Me
  5. vue-cli 3.0脚手架搭建项目
  6. 【软工实践】Alpha冲刺(5/6)
  7. powshell 输出字符编码的问题,设置为utf-8
  8. (mac)Idea安装配置maven
  9. Sword 第三方库介绍二
  10. Java算法 -- 桶排序