0

そこで、https: //docs.djangoproject.com/en/dev/topics/db/multi-db/ にある複数のデータベースのドキュメントを読みましたが、かなり役に立ちました。setting.py で 2 番目のデータベースを表示する方法と、コマンド プロンプトを介して同期する方法を取得しました。しかし、私が理解できないのは、特定のモデルを2番目のデータベースに同期/保存する方法を指定する方法です。特に私が明示的に述べていない場合。

ユーザーのように。

Django の users クラスを使用してユーザーを作成している場合、どうすればそれを 2 番目のデータベースに保存できますか?

4

2 に答える 2

1

(Django DOCSから直接コーディング:https ://docs.djangoproject.com/en/dev/topics/db/multi-db/#automatic-database-routing

ルーターは、データを取得または設定するデータベースを処理します。

アプリケーション用のルーター(「myapp」という名前)が必要な場合

class MyAppRouter(object):
        """A router to control all database operations on models in
        the myapp application"""

        def db_for_read(self, model, **hints):
            "Point all operations on myapp models to 'other'"
            if model._meta.app_label == 'myapp':
                return 'other'
            return None

        def db_for_write(self, model, **hints):
            "Point all operations on myapp models to 'other'"
            if model._meta.app_label == 'myapp':
                return 'other'
            return None

        def allow_relation(self, obj1, obj2, **hints):
            "Allow any relation if a model in myapp is involved"
            if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
                return True
            return None

        def allow_syncdb(self, db, model):
            "Make sure the myapp app only appears on the 'other' db"
            if db == 'other':
                return model._meta.app_label == 'myapp'
            elif model._meta.app_label == 'myapp':
                return False
            return None

settings.pyに次の行を追加することにより、すべての「myapp」アプリケーションデータが独自のデータベース(「other」という名前)で作成/保存/処理されます。残りのすべてのアプリケーションは、デフォルトのデータベースを使用します。

DATABASE_ROUTERS = ['path.to.MyAppRouter']

ルーターはどこにでも保存できます。settings.DATABASE_ROUTERSのパスを修正するだけです。

于 2012-04-18T20:00:42.387 に答える
1

提供したドキュメントをもう一度注意深くお読みください。ドキュメントの自動データベースルーティングセクションは、あなたの質問に正確に答えます。
ユーザーDBのルーティングは、実際の使用法とパーティションポリシーによって異なり、1文の答えはありません。ユーザー向けのドキュメント内に例があり、ローカルマシンを読んでチェックインできます。

于 2012-04-18T07:57:27.837 に答える