파이문

[django] django에서 데이터베이스 여러개 사용하기 본문

Python/django

[django] django에서 데이터베이스 여러개 사용하기

민Z 2018. 3. 18. 16:04

django에서 데이터 베이스 여러개 사용하기

(django multiple database)



django에서 데이터베이스를 여러개 사용하려고 하는 경우 인터넷에서 검색해보면 router를 사용하라고 대부분이 말해주고 있다.

(아래의 예시는 2.0 기준이며 모두 공식 홈페이지 레퍼런스를 참고 하였다.)


django는 db router 라는 것을 제공하는데, setting에서 지정한 django naming을 따라서 각각 다른 데이터베이스로 연결해주는 클래스라고 보면 된다. 예제를 통해 정리해보면, 우선 settings.py 에 데이터베이스의 정보를 저장해놓을 것이다. 바로 아래 처럼.

DATABASES = {
    'default': {},
    'auth_db': {
        'NAME': 'auth_db',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'swordfish',
    },
    'user': {
        'NAME': 'user',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'spam',
    },

}

default는 django에서 제공하는 admin, session, log 테이블이 생성되는 곳이고, 그 외의 데이터 베이스는 기존에 있던, 혹은 다르게 사용할 데이터 베이스를 의미한다.


이렇게 settings.py 에 적어놓았다면, 그 다음에 할 일은 router.py 라는 파일을 나의 django app 아래에 두고 아래 처럼 적는다. (정확히 위치는 중요하지 않다. 어차피 어느 위치의 db router를 참조할 것인지 settings.py 에 적어둘 것이다.)


class AuthRouter:
    """
    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

그리고 settings.py 에 아래와 같은 내용을 추가 한다.

DATABASE_ROUTERS = ['path.to.AuthRouter']

path.to는 AuthRouter가 위치하는 곳이다. 만약 polls 밑에 router.py에 AuthRouter가 있다면 내용은 [polls.router.AuthRouter]가 될 것이다.


여기까지 해 두고, 다른 app에서 사용할 때, 제대로 동작하지 않는 것 같다면, 혹시 app_label이 제대로 적혀있나 확인해보도록 하자.


inspectdb로 모델을 생성하는 경우 app_label이 없을 수도 있다. class Meta 밑에  app_label을 적고, 해당 app_label로 router가 제대로 분기하고 있는지 확인해보면 좋을 것이다.



출처

https://docs.djangoproject.com/en/2.0/topics/db/multi-db/

'Python > django' 카테고리의 다른 글

[django] 템플릿에서 Custom tag / filter 사용하기  (0) 2018.03.05
Comments