关于django操作orm的一些事--反向生成orm、连接多个数据库
1. django反向生成orm的类代码
使用命令python manage.py inspectdb > app01/models.py
,注意,我这里的app01是app的名字。
2.django连接多个数据库
在很多情况下,一个项目里面不止一个app,也不止使用一个库,那么就面临着连接多个数据库的问题。
那么先来说说,如何连接使用多个app连接多个数据库:
以mysql为例:
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():