你可以做一个通用路由器,它是使用一个dict 配置的应用程序去一个非默认数据库。
app_to_database = {
'django_cache': 'the_declared_name_of_the_cache_database',
}
class CacheRouter(object):
def db_for_read(self, model, **hints):
return app_to_database.get(model._meta.app_label, None)
def db_for_write(self, model, **hints):
return app_to_database.get(model._meta.app_label, None)
def allow_syncdb(self, db, model):
_db = app_to_database.get(model._meta.app_label, None)
return db == _db if _db else None
编辑:更好的解释
如果您想使用不同的架构,或数据库服务器,甚至完全不同的后端,您需要在settings.py 中声明它们:
DATABASES = {
'default': # the one storing your app data
{ 'NAME': 'main_db', # this is the schema name
'USER': '...',
'PASSWORD': '...',
'ENGINE': '...', # etc...
},
'the_declared_name_of_the_cache_database': # the name is arbitrary here
{ 'NAME': 'db_for_djcache', # this is the schema name
'USER': '...',
'PASSWORD': '...',
'ENGINE': '...', # etc...
},
}
DATABASE_ROUTERS = ['path.to.MyAppRouter'] # that is, the module.ClassName of the
# router class you defined above.
另一方面,如果您似乎从您的评论中暗示,您只需要一个不同的表(在同一架构内),您根本不需要路由器,一切都由 django 顺利管理。
您可以使用任何 GUI 客户端检查数据库发生的情况。只需打开您的架构(ta)并检查表格及其内容。