Djangoでdb接続情報を複数設定する
普通にdjangoプロジェクトを作成するとdb設定の初期値は以下のようになってます
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
DATABASESは辞書になってるので'default'以外にも名前をつけてやれば複数設定することができますね。
適当に'another'を設定してみました。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'default.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
},
'another': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'another.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
適当にモデルを作成して、syncdbしたら、default.dbにテーブルが作成されました。
another.dbのほうにテーブルを作成するには、--databaseオプションでデータベース名を指定します
$ python manage.py syncdb --database=another
djangoのormでデータの取得や保存を行う場合は、以下のようにusing関数を使って、対象のdbを指定します
>>> from apps.models import Book
>>> Book.objects.using('default').create(title=u'Python プロフェッショナルプログラミング')
Out[21]: <Book: Book object>
>>> Book.objects.using('default').all()
Out[22]: [<Book: Book object>]
>>> Book.objects.using('another').all()
Out[23]: []
cursorを使う場合はconnectionsから名前を指定してconnectionを取得して、そこからcursorを取得します
>>>from django.db import connections
>>> con = connections['another']
>>> cursor = con.cursor()
>>> cursor.execute('select * from apps_book')
Out[30]: <django.db.backends.sqlite3.base.SQLiteCursorWrapper at 0x1049802b0>
>>> cursor.fetchall()
Out[32]: []