VR侍

主に興味があって調べたことについてまとめていきます。

DjangoのDBをPostgreSQLに変更する

Djangoで作成したWebアプリを、Herokuにアップして使用できるようにしたい。
DjangoDBMSの設定はデフォルトでは、SQLiteになっているが、
Herokuは Postgressを推奨しているため、先ずはその設定をしたい。

状況整理、自分の環境は以下の通り。
Windows 10
Python 3.5.1
PostgreSQL 9.5
Django 1.9.7

PythonでPosgreSQLを使用するためには、psycopg2というライブラリを入れる必要があるが、
上記の環境だと通常通り入れようとするとエラーになってしまう。

以下のページを参考にさせていただきました。
http://prunus1350.hatenablog.com/entry/2016/01/09/135110

ただし、ページに書かれていた名称のものが見当たらなかったため、
代わりに psycopg2-2.6.1-cp35-cp35m-win_amd64.whl を用いた。

Pythonコンソールにて以下を実行することでインストール成功の確認ができる。
>>> import psycopg2
>>>

postgresにパスワードなしでログインする方法
C:\Program Files\PostgreSQL\9.5\data\pg_hba.conf
の、

# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5

# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust

に書き換える

次に、管理者権限でコンソールを開いて

net stop postgresql-x64-9.5
net start postgresql-x64-9.5

してサービスを再起動後、
psql -U postgress でログインできる。

次に、settings.py のデータベース設定を公式を参考に以下のように変更。
DB名やユーザ名などは初期設定のまま。

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
 'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD' : '',
'HOST' : '127.0.0.1',
'PORT' : 5432,
}
}

そして、マイグレーションの実行
python manage.py migrate

Operations to perform:
Apply all migrations: sessions, admin, auth, contenttypes
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying sessions.0001_initial... OK

よさそうである。