2013-08-13 1 views
2

에서 인증 나는 두 DATABASES 내 장고 프로젝트에 구성되어 :장고 다중 DB, 비 기본 DB

  • default
  • reports

reports 데이터베이스가 auth_user을 포함하지만, 동시에 사용자를 인증 , 사용자는 default 데이터베이스에서 확인됩니다. reports 데이터베이스와 함께 authenticate()을 어떻게 사용할 수 있습니까?

the Django documentation와 같이이 상황을 정확히 이런 종류의를 포함하는 사용자 지정 데이터베이스 라우터를 사용하여이 작업을 수행 할 수

답변

0

:

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을 명시 적으로 사용하는 것이 더 쉽습니다.