我DATABASES
在我的 Django 项目中配置了两个:
default
reports
reports
数据库包含auth_user
,但在对用户进行身份验证时,会在数据库中检查用户default
。我如何authenticate()
与reports
数据库一起使用?
我DATABASES
在我的 Django 项目中配置了两个:
default
reports
reports
数据库包含auth_user
,但在对用户进行身份验证时,会在数据库中检查用户default
。我如何authenticate()
与reports
数据库一起使用?
您可以使用自定义数据库路由器来执行此操作,如Django 文档中所示,该文档正好涵盖了这种情况:
class AuthRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to reports.
"""
if model._meta.app_label == 'auth':
return 'reports'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to reports.
"""
if model._meta.app_label == 'auth':
return 'reports'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'auth' or \
obj2._meta.app_label == 'auth':
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the auth app only appears in the 'reports'
database.
"""
if db == 'reports':
return model._meta.app_label == 'auth'
elif model._meta.app_label == 'auth':
return False
return None
您需要将该类的虚线路径放入DATABASE_ROUTERS
您的settings.py
.
有一些关于将 Django contrib 应用程序与多个数据库一起使用的注意事项值得一读。特别是,auth
您需要的ContentType
表以及同一个数据库中的后备表。
将您的默认设置设为默认值可能更容易reports
,并且仅根据需要使用您当前default
显式调用的那个。