关于django操作orm的一些事--反向生成orm、连接多个数据库
2024-10-20 03:48:03
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
即可解决此问题。
最新文章
- chrome中hack解决input:-webkit-autofill自定义样式
- Server Transfer()和Response.Redirect()的使用
- UVA_393_Doors_(计算几何基础+最短路)
- gridView 布局间距合理化的有效办法
- python学习之路-5 基础进阶篇
- FZUOJ Problem 2178 礼品配送
- SQL Server 连接问题-命名管道
- Selenium自动化-调用Mysql数据库
- vue-cli的跨域配置(自己总结)
- 编译openwrt时报错:g++: internal compiler error: Killed (program cc1plus)
- webpack之牛刀小试 打包并压缩html、js
- jQuery 位置
- js 实现List
- 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.
- web前端----Bootstrap框架
- Entities、pads、links 实体、垫、链接
- Ubuntu-18.04Python2与Python3自由切换
- APP 渠道推广【摘自网络】
- windows7开机后,罗技k380无法自动连接解决办法
- light table 添加行号 更新