我在Django项目中配置了两个DATABASES
:
default
reports
reports
数据库包含auth_user
,但在对用户进行身份验证时,会在default
数据库中检查用户。如何将authenticate()
与reports
数据库一起使用?
答案 0 :(得分:0)
您可以使用自定义数据库路由器执行此操作,如the Django documentation中所示,其中包含此类情况:
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
。
有some notes about using Django contrib apps with multiple databases值得一读。特别是,除了auth
表之外,您还需要同一数据库中的ContentType
支持表。
将reports
作为默认设置可能更容易,并且只能根据需要明确使用您当前正在呼叫的default
。