2

DATABASESDjango プロジェクトで2 つを構成しています。

  • default
  • reports

reportsデータベースには が含まれていauth_userますが、ユーザーの認証中にユーザーがdefaultデータベースでチェックされます。authenticate()データベースをどのように使用できreportsますか?

4

1 に答える 1

0

この種の状況を正確にカバーしている 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_ROUTERSsettings.py.

複数のデータベースで Django contrib アプリを使用する場合の注意事項がいくつかあります。特に、テーブルと同様に、同じデータベース内authのバッキング テーブルが必要です。ContentType

必要に応じて、デフォルトを作成し、現在明示的にreports呼び出しているもののみを使用する方が簡単な場合があります。default

于 2013-08-13T08:31:28.047 に答える