Django Multiple DB,从NON默认db进行身份验证

时间:2013-08-13 08:14:55

标签: python django django-orm

我在Django项目中配置了两个DATABASES

  • default
  • reports

reports数据库包含auth_user,但在对用户进行身份验证时,会在default数据库中检查用户。如何将authenticate()reports数据库一起使用?

1 个答案:

答案 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