从这里开始,我将遵循如何在一个Django项目中处理多个数据库的说明。
topics/db/multi-db
我已经创建了所需的两个路由器。
它们被保存为./database_routers/declaration.py和./database_routers/wordpress.py。
/database_routers/declaration.py的内容是
class DiscourseRouter:
"""
A router to control all database operations on models in the
discourse application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read discourse models go to discourse.
"""
if model._meta.app_label == 'discourse':
return 'discourse'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write discourse models go to discourse.
"""
if model._meta.app_label == 'discourse':
return 'discourse'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the discourse app is involved.
"""
if obj1._meta.app_label == 'discourse' or \
obj2._meta.app_label == 'discourse':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the discourse app only appears in the 'discourse'
database.
"""
if app_label == 'discourse':
return db == 'discourse'
return None
/database_routers/wordpress.py的内容是
class WordpressRouter:
"""
A router to control all database operations on models in the
wordpress application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read wordpress models go to wordpress.
"""
if model._meta.app_label == 'wordpress':
return 'wordpress'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write wordpress models go to wordpress.
"""
if model._meta.app_label == 'wordpress':
return 'wordpress'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the wordpress app is involved.
"""
if obj1._meta.app_label == 'wordpress' or \
obj2._meta.app_label == 'wordpress':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the wordpress app only appears in the 'wordpress'
database.
"""
if app_label == 'wordpress':
return db == 'wordpress'
return None
我创造了一个空的
./database_routers/__init__.py
文件
我设置的api/设置中的数据库路由器设置
DATABASE_ROUTERS = ['database_routers.DiscourseRouter', 'database_routers.WordpressRouter']
当我尝试使用Shell Plus查看项目时,
./manage.py shell_plus
我得到
ImportError: Module "database_routers" does not define a "DiscourseRouter" attribute/class
如何将数据库路由器添加到django项目中,以便python识别路径目录“name.classname”?