Django多数据库配置及逆向生成model教程


Posted in Python onMarch 28, 2020

在项目中我们每个app对应不同的数据库,其中有一个是从数据库逆向生成model,做个笔记。

1、修改项目的setting.py配置 :

DATABASES = {
 'default': {
  'ENGINE': 'django.db.backends.mysql', # 默认用mysql
  'NAME': 'bk',      # 数据库名 (默认与APP_ID相同)
  'USER': 'root',      # 你的数据库user
  'PASSWORD': 'root',      # 你的数据库password
  'HOST': 'xxx.xxx.xxx.xxx',     # 开发的时候,使用localhost
  'PORT': '3306',      # 默认3306
 },
 'cloudsino_test': {
   'ENGINE': 'django.db.backends.mysql', # 默认用mysql
   'NAME': 'cloudsino_test',      # 数据库名 (默认与APP_ID相同)
   'USER': 'root',      # 你的数据库user
   'PASSWORD': 'root',      # 你的数据库password
   'HOST': 'xxx.xxx.xxx.xxx',     # 开发的时候,使用localhost
   'PORT': '3306',      # 默认3306
  },
}

# 设置数据库的路由规则方法
DATABASE_ROUTERS = ['conf.database_router.DatabaseAppsRouter']

# 设置APP对应的数据库路由表,哪个app要连接哪个数据库,没有指定会用default那个。
DATABASE_APPS_MAPPING = {
 # example:
 #'app_name':'database_name',
 'home_application': 'cloudsino_test',
 'cmdb': 'default',
}

2、新建database_router.py:

在与setting.py文件同级的目录下新建database_router.py文件:

# -*- coding: utf-8 -*-
from settings_development import DATABASE_APPS_MAPPING

DATABASE_MAPPING = DATABASE_APPS_MAPPING


class DatabaseAppsRouter(object):
 def db_for_read(self, model, **hints):
  """"建议model类型对象从哪一个数据库读取."""
  if model._meta.app_label in DATABASE_MAPPING:
   return DATABASE_MAPPING[model._meta.app_label]
  return None

 def db_for_write(self, model, **hints):
  """建议model类型对象的写入操作应该使用哪个数据库"""
  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.
  	如果obj1 和obj2 之间应该允许关联则返回True,如果应该防止关联则返回False,如果路由无法判断则返回None
  """
  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.
  定义迁移操作是否允许在别名为db的数据库上运行。如果操作应该运行则返回True ,如果不应该运行则返回False,如果路由无法判断则返回None。
  """
  if db in DATABASE_MAPPING.values():
   return DATABASE_MAPPING.get(app_label) == db
  elif app_label in DATABASE_MAPPING:
   return False
  return None

3.逆向生成model:

在terminal中输入以下命令,使用名为cloudsino_test的DATABASE来逆向生成model到home_application这个app的models.py:

python manage.py inspectdb --database=cloudsino_test > home_application/models.py

Django多数据库配置及逆向生成model教程

逆向生成的model:

# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]'
# into your database.
from __future__ import unicode_literals

from django.db import models


class CloudsinoCpuinfo(models.Model):
 corenumber = models.CharField(max_length=128)
 frequency = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 name = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 device = models.ForeignKey('CloudsinoDevice', blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_cpuinfo'


class CloudsinoDevice(models.Model):
 sn = models.CharField(max_length=128)
 app = models.CharField(max_length=128)
 business_chargeby1 = models.CharField(max_length=128)
 business_chargeby2 = models.CharField(max_length=128)
 chargeby1 = models.CharField(max_length=128)
 chargeby2 = models.CharField(max_length=128)
 description = models.CharField(max_length=128)
 device_status = models.CharField(max_length=128)
 devicename = models.CharField(max_length=128)
 field1 = models.CharField(max_length=128)
 field2 = models.CharField(max_length=128)
 field3 = models.CharField(max_length=128)
 field4 = models.CharField(max_length=128)
 field5 = models.CharField(max_length=128)
 frame_posiniton = models.CharField(max_length=128)
 framename = models.CharField(max_length=128)
 ip = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 model = models.CharField(max_length=128)
 os = models.CharField(max_length=128)
 position_desc = models.CharField(max_length=128)
 roomarea = models.CharField(max_length=128)
 roomname = models.CharField(max_length=128)
 servicetag = models.CharField(max_length=128)
 shape = models.CharField(max_length=128)
 specification = models.CharField(max_length=128)
 subtype = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 ucount = models.CharField(max_length=128)

 class Meta:
  managed = False
  db_table = 'cloudsino_device'


class CloudsinoDevicetype(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 status = models.CharField(max_length=128)

 class Meta:
  managed = False
  db_table = 'cloudsino_devicetype'


class CloudsinoDiskinfo(models.Model):
 bus = models.CharField(max_length=128)
 formfactor = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 media = models.CharField(max_length=128)
 name = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 size = models.CharField(max_length=128)
 speed = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_diskinfo'


class CloudsinoFaninfo(models.Model):
 index = models.CharField(max_length=128)
 name = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_faninfo'


class CloudsinoHbacardinfo(models.Model):
 name = models.CharField(max_length=128)
 wwnn = models.CharField(max_length=128)
 wwpn = models.CharField(max_length=128)
 fc_switch = models.CharField(max_length=128)
 switch_port = models.CharField(max_length=128)
 switch_mac = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_hbacardinfo'


class CloudsinoManageinfo(models.Model):
 assetcode = models.CharField(max_length=128)
 department = models.CharField(max_length=128)
 express_code = models.CharField(max_length=128)
 service_level = models.CharField(max_length=128)
 shutdown_level = models.CharField(max_length=128)
 usage = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_manageinfo'


class CloudsinoManufacturertype(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 status = models.CharField(max_length=128)

 class Meta:
  managed = False
  db_table = 'cloudsino_manufacturertype'


class CloudsinoMemory(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 frequency = models.CharField(max_length=128)
 size = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 memoryinfo = models.ForeignKey('CloudsinoMemoryinfo', blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_memory'


class CloudsinoMemoryinfo(models.Model):
 max_dimmslots = models.CharField(max_length=128)
 mem_totalsize = models.CharField(max_length=128)
 memmax_capacitysize = models.CharField(max_length=128)
 populated_dimmslots = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_memoryinfo'


class CloudsinoNetworkinfo(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 mac = models.CharField(max_length=128)
 speed = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_networkinfo'


class CloudsinoOobnetwork(models.Model):
 ip = models.CharField(max_length=128)
 netmask = models.CharField(max_length=128)
 gateway = models.CharField(max_length=128)
 mac = models.CharField(max_length=128)
 ethernet_switch = models.CharField(max_length=128)
 swith_port = models.CharField(max_length=128)
 swith_mac = models.CharField(max_length=128)
 distribution_frame = models.CharField(max_length=128)
 distribution = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_oobnetwork'


class CloudsinoPciecard(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 loc = models.CharField(max_length=128)
 online_state = models.CharField(max_length=128)
 conntype = models.CharField(max_length=128)
 bandwidth = models.CharField(max_length=128)
 speed = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_pciecard'


class CloudsinoPowerinfo(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 model = models.CharField(max_length=128)
 outputpower = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_powerinfo'


class CloudsinoProductnetwork(models.Model):
 ip = models.CharField(max_length=128)
 netmask = models.CharField(max_length=128)
 gateway = models.CharField(max_length=128)
 mac = models.CharField(max_length=128)
 os = models.CharField(max_length=128)
 remote_type = models.CharField(max_length=128)
 remote_port = models.CharField(max_length=128)
 ethernet_switch = models.CharField(max_length=128)
 swith_port = models.CharField(max_length=128)
 swith_mac = models.CharField(max_length=128)
 distribution_frame = models.CharField(max_length=128)
 distribution = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_productnetwork'


class CloudsinoPurchasewarrantyinfo(models.Model):
 date_manuf = models.CharField(max_length=128)
 expiredate = models.CharField(max_length=128)
 price = models.CharField(max_length=128)
 purchase_order = models.CharField(max_length=128)
 purchase_order_name = models.CharField(max_length=128)
 purchase_supply = models.CharField(max_length=128)
 serviceagent = models.CharField(max_length=128)
 warrantyitem = models.CharField(db_column='warrantyItem', max_length=128) # Field name made lowercase.
 warrantyperiod = models.CharField(db_column='warrantyPeriod', max_length=128) # Field name made lowercase.
 warrantystartdate = models.CharField(db_column='warrantyStartDate', max_length=128) # Field name made lowercase.
 warrantytype = models.CharField(db_column='warrantyType', max_length=128) # Field name made lowercase.
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_purchasewarrantyinfo'


class CloudsinoRaidinfo(models.Model):
 name = models.CharField(max_length=128)
 type = models.CharField(max_length=128)
 cachesize = models.CharField(max_length=128)
 speed = models.CharField(max_length=128)
 manufacturer = models.CharField(max_length=128)
 partnumber = models.CharField(max_length=128)
 serialnumber = models.CharField(max_length=128)
 index = models.CharField(max_length=128)
 device = models.ForeignKey(CloudsinoDevice, blank=True, null=True)

 class Meta:
  managed = False
  db_table = 'cloudsino_raidinfo'


class DjangoMigrations(models.Model):
 app = models.CharField(max_length=255)
 name = models.CharField(max_length=255)
 applied = models.DateTimeField()

 class Meta:
  managed = False
  db_table = 'django_migrations'

补充知识:Django使用数据库生成模型类

正常的开发流程

在models.py中定义模型类,要求继承自models.Model

把应用加入settings.py文件的installed_app项

生成迁移文件

执行迁移生成表

使用模型类进行crud操作

使用数据库生成模型类

python manage.py inspectdb > app_name/models.py

例如:

python manage.py inspectdb > booktest/models.py

以上这篇Django多数据库配置及逆向生成model教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中的__init__ 、__new__、__call__小结
Apr 25 Python
使用grappelli为django admin后台添加模板
Nov 18 Python
win10下Python3.6安装、配置以及pip安装包教程
Oct 01 Python
python学习笔记之列表(list)与元组(tuple)详解
Nov 23 Python
Python实现的简单排列组合算法示例
Jul 04 Python
python中bs4.BeautifulSoup的基本用法
Jul 27 Python
从numpy数组中取出满足条件的元素示例
Nov 26 Python
Python类中self参数用法详解
Feb 13 Python
Python 输出详细的异常信息(traceback)方式
Apr 08 Python
新手学python应该下哪个版本
Jun 11 Python
python中uuid模块实例浅析
Dec 29 Python
Python实现PIL图像处理库绘制国际象棋棋盘
Jul 16 Python
后端开发使用pycharm的技巧(推荐)
Mar 27 #Python
如何基于python3和Vue实现AES数据加密
Mar 27 #Python
python小程序基于Jupyter实现天气查询的方法
Mar 27 #Python
Python实现的北京积分落户数据分析示例
Mar 27 #Python
Pyspark获取并处理RDD数据代码实例
Mar 27 #Python
Python Django中的STATIC_URL 设置和使用方式
Mar 27 #Python
Python爬虫爬取、解析数据操作示例
Mar 27 #Python
You might like
随机广告显示(PHP函数)
2006/10/09 PHP
thinkPHP3.2.3实现阿里大于短信验证的方法
2018/06/06 PHP
php解决安全问题的方法实例
2019/09/19 PHP
Jquery实现搜索框提示功能示例代码
2013/08/13 Javascript
JavaScript中split() 使用方法汇总
2015/04/17 Javascript
情人节单身的我是如何在敲完代码之后收到12束玫瑰的(javascript)
2015/08/21 Javascript
JavaScript获取function所有参数名的方法
2015/10/30 Javascript
JS实现选项卡实例详解
2015/11/17 Javascript
html5+javascript实现简单上传的注意细节
2016/04/18 Javascript
JS获取复选框的值,并传递到后台的实现方法
2016/05/30 Javascript
详解JavaScript时间处理之几个月前或几个月后的指定日期
2016/12/21 Javascript
关于vue.extend和vue.component的区别浅析
2017/08/16 Javascript
js将当前时间格式化为 年-月-日 时:分:秒的实现代码
2018/01/20 Javascript
微信小程序实现banner图轮播效果
2020/06/28 Javascript
如何在微信小程序中实现Mixins方案
2019/06/20 Javascript
webpack4.0+vue2.0利用批处理生成前端单页或多页应用的方法
2019/06/28 Javascript
JS控制只能输入数字并且最多允许小数点两位
2019/11/24 Javascript
[01:03:36]Ti4 循环赛第三日DK vs Titan
2014/07/12 DOTA
跟老齐学Python之从if开始语句的征程
2014/09/14 Python
python通过imaplib模块读取gmail里邮件的方法
2015/05/08 Python
Python实现控制台输入密码的方法
2015/05/29 Python
python基础教程之分支、循环简单用法
2016/06/16 Python
python实现超简单的视频对象提取功能
2018/06/04 Python
pip install urllib2不能安装的解决方法
2018/06/12 Python
python 中的9个实用技巧,助你提高开发效率
2020/08/30 Python
Python利用imshow制作自定义渐变填充柱状图(colorbar)
2020/12/10 Python
vivo智能手机官方商城:vivo
2016/09/22 全球购物
STAUD官方网站:洛杉矶独有的闲适风格
2019/04/11 全球购物
高中微机老师自我鉴定
2014/02/16 职场文书
家居装修公司创业计划书范文
2014/03/20 职场文书
爱岗敬业演讲稿
2014/05/05 职场文书
2014市国税局对照检查材料思想汇报
2014/09/23 职场文书
合同权益转让协议书模板
2014/11/18 职场文书
《语言的突破》读后感3篇
2019/12/12 职场文书
WebWorker 封装 JavaScript 沙箱详情
2021/11/02 Javascript
5人制售《绝地求生》游戏外挂获利500多万元 被判刑
2022/03/31 其他游戏