ホームページ  >  記事  >  ウェブフロントエンド  >  Django が複数のデータベース メソッドを使用する方法の概要

Django が複数のデータベース メソッドを使用する方法の概要

巴扎黑
巴扎黑オリジナル
2017-09-07 10:17:081507ブラウズ

一部のプロジェクトには複数のデータベースの使用が含まれる場合がありますが、その方法は非常に簡単です。次に、この記事では Django で複数のデータベースを使用する方法を紹介します。必要な方は参考にしてください。

プロジェクトによっては、複数のデータベースを使用する場合もあります。

1. 設定で DATABASE を設定します

たとえば、2 つのデータベースを使用する場合:


DATABASES = {
  'default': {
    'NAME': 'app_data',
    'ENGINE': 'django.db.backends.postgresql',
    'USER': 'postgres_user',
    'PASSWORD': 's3krit'
  },
  'users': {
    'NAME': 'user_data',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'priv4te'
  }
}

このようにして、2 つのデータベースが決定され、1 つはデフォルト、もう 1 つはユーザーになります。データベースの別名は任意に決定できます。

default のエイリアスは非常に特殊で、モデルがルート内で特に選択されていない場合、デフォルトでデフォルトのデータベースが使用されます。

もちろん、デフォルトを空に設定することもできます:


DATABASES = {
  'default': {},
  'users': {
    'NAME': 'user_data',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'superS3cret'
  },
  'customers': {
    'NAME': 'customer_data',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_cust',
    'PASSWORD': 'veryPriv@ate'
  }
}

この方法では、デフォルトのデータベースがないため、使用されているサードパーティ ライブラリのモデルを含むすべてのモデルに対してデータベース ルーティングを選択する必要があります。

2. データベースを選択する必要があるモデルの app_label を指定します


class MyUser(models.Model):
  ...
  class Meta:
    app_label = 'users'

3. データベースルーターを作成します

データベースルーターは、主に次の 4 つのメソッドを定義します。

db_for_read(model, **hints)db_for_read(model, **hints)

规定model使用哪一个数据库读取。

db_for_write(model, **hints)

规定model使用哪一个数据库写入。

allow_relation(obj1, obj2, **hints)

确定obj1和obj2之间是否可以产生关联, 主要用于foreign key和 many to many操作。

allow_migrate(db, app_label, model_name=None, **hints)

は、モデルの読み取りに使用するデータベースを指定します。

db_for_write(model, **hints)

モデルの書き込みに使用するデータベースを指定します。

allow_relation(obj1, obj2, **hints)


obj1 と obj2 を関連付けることができるかどうかを決定します。主に外部キーと多対多の操作に使用されます。

allow_merge(db, app_label, model_name=None, **hints)

エイリアス db を使用してデータベース上で移行操作を実行できるかどうかを決定します。

完全な例:

データベース設定:

DATABASES = {
  'default': {},
  'auth_db': {
    'NAME': 'auth_db',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'swordfish',
  },
  'primary': {
    'NAME': 'primary',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'spam',
  },
  'replica1': {
    'NAME': 'replica1',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'eggs',
  },
  'replica2': {
    'NAME': 'replica2',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'bacon',
  },
}

次の効果を達成したい場合:

app_label が auth であるモデルの読み取りと書き込みは auth_db で完了し、モデルの残りの部分は完了します書き込みはプライマリで完了し、読み取りはレプリカ1とレプリカ2でランダムに行われます。

auth:

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 auth_db.
    """
    if model._meta.app_label == 'auth':
      return 'auth_db'
    return None
  def db_for_write(self, model, **hints):
    """
    Attempts to write auth models go to auth_db.
    """
    if model._meta.app_label == 'auth':
      return 'auth_db'
    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_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the auth app only appears in the 'auth_db'
    database.
    """
    if app_label == 'auth':
      return db == 'auth_db'
    return None

このようにして、app_label が auth である Model の読み取りと書き込みは auth_db で完了し、関連付けは auth_db データベースでのみ実行できます。

残り:

import random
class PrimaryReplicaRouter(object):
  def db_for_read(self, model, **hints):
    """
    Reads go to a randomly-chosen replica.
    """
    return random.choice(['replica1', 'replica2'])
  def db_for_write(self, model, **hints):
    """
    Writes always go to primary.
    """
    return 'primary'
  def allow_relation(self, obj1, obj2, **hints):
    """
    Relations between objects are allowed if both objects are
    in the primary/replica pool.
    """
    db_list = ('primary', 'replica1', 'replica2')
    if obj1._state.db in db_list and obj2._state.db in db_list:
      return True
    return None
  def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    All non-auth models end up in this pool.
    """
    return True

このように、readはreplica1とreplica2でランダムに行われ、書き込みはprimaryを使用します。

最後に設定で設定します:

DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']

、それだけです。

移行操作を実行する場合:


$ ./manage.py migrate
$ ./manage.py migrate --database=users

移行操作はデフォルトでデフォルトのデータベースで操作されます。他のデータベースで操作するには、--database オプションの後にデータベースのエイリアスを使用します。

同様に、dbshel​​l、dumpdata、loaddata コマンドにはすべて --database オプションが付いています。

ルートを手動で選択することもできます:

クエリ:


>>> # This will run on the 'default' database.
>>> Author.objects.all()
>>> # So will this.
>>> Author.objects.using('default').all() 
>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()

保存:

>>> my_object.save(using='legacy_users')
移動:

>>> p = Person(name='Fred')
>>> p.save(using='first') # (statement 1)
>>> p.save(using='second') # (statement 2)

上記のコードは、p が最初の場合に問題が発生します。データベース 初めて保存するとき、デフォルトで主キーが生成されるため、2 番目のデータベースを使用して保存するとき、p にはすでに主キーがあり、この主キーが使用されていない場合は問題が発生しませんが、使用されている場合は問題が発生しません。以前に使用した場合、元のデータは上書きされます。

2 つの解決策があります:

1. 保存する前に主キーをクリアします:


>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.pk = None # Clear the primary key.
>>> p.save(using='second') # Write a completely new object.

を使用して削除します:

から削除


🎜
>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.save(using='second', force_insert=True)
🎜 オブジェクトを Legacy_users データベースから new_users データベースに移動する場合: 🎜🎜🎜🎜
>>> u = User.objects.using('legacy_users').get(username='fred')
>>> u.delete() # will delete from the `legacy_users` database

以上がDjango が複数のデータベース メソッドを使用する方法の概要の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。