>  기사  >  웹 프론트엔드  >  Django가 다양한 데이터베이스 메소드를 사용하는 방법 소개

Django가 다양한 데이터베이스 메소드를 사용하는 방법 소개

巴扎黑
巴扎黑원래의
2017-09-07 10:17:081505검색

일부 프로젝트에는 여러 데이터베이스를 사용할 수 있으며 방법은 매우 간단합니다. 다음으로 이 글에서는 Django에서 다중 데이터베이스를 사용하는 방법을 소개하겠습니다. 필요하신 분들은 참고하시면 됩니다

일부 프로젝트에서는 다중 데이터베이스를 사용하는 방법이 매우 간단합니다.

1. 설정에서 DATABASE를 설정하세요

예를 들어 두 개의 데이터베이스를 사용하려는 경우:


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'
  }
}

이런 식으로 두 개의 데이터베이스가 결정됩니다. 하나는 기본값이고 다른 하나는 사용자입니다. 데이터베이스의 별칭은 임의로 결정할 수 있습니다.

기본 별칭은 매우 특별합니다. 경로에서 모델을 구체적으로 선택하지 않으면 기본적으로 기본 데이터베이스가 사용됩니다.

물론 기본값을 공백으로 설정할 수도 있습니다.


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. 데이터베이스 라우터 쓰기

데이터베이스 라우터는 주로 다음 네 가지 방법을 정의하는 데 사용됩니다.

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_ migration(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에서 완료되고 모델의 나머지 부분은 완료됩니다. Primary에서는 쓰기가 완료되고, Replica1과 Replica2에서는 무작위로 읽기가 수행됩니다.

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인 모델의 읽기 및 쓰기가 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

이렇게 읽기는 Replica1과 Replica2에서 무작위로 이루어지며, 쓰기는 Primary를 사용합니다.

마지막으로 설정에서 설정하세요:

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

그게 전부입니다.

마이그레이션 작업을 수행하는 경우:


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

마이그레이션 작업은 기본적으로 기본 데이터베이스에서 작동합니다. 다른 데이터베이스에서 작업하려면 --database 옵션과 데이터베이스 별칭을 사용할 수 있습니다.

따라서 dbshell, 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가 처음에 올 때 문제를 일으킬 것입니다. 데이터베이스 처음 저장할 때 기본 키가 기본적으로 생성되므로 두 번째 데이터베이스를 사용하여 저장할 때 p에는 이미 기본 키가 있으므로 이 기본 키를 사용하지 않으면 문제가 되지 않습니다. 이전에 사용한 경우 원본 데이터를 덮어쓰게 됩니다. weconder 1 차는 SAVING a worde a wecond a wecond a wected : , 그리고 삭제

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

레거시_users 데이터베이스에서 new_users 데이터베이스로 개체를 이동하려는 경우:

>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.save(using='second', force_insert=True)

위 내용은 Django가 다양한 데이터베이스 메소드를 사용하는 방법 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.