3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Django2をMySQLに接続する Windows10版

Posted at

前提条件

Windows10
Python 3.6.0
Django 2.1.1

MySQLのインストール

以下のページを参考にWindows版MySQLのインストール
https://webkaru.net/mysql/install-windows/

参考先でページでは、MySQL 5.6のインストール手順を示されている。
最新版はMySQL 8.0であるので、読み替えてインストールを行った。

PyMySQLのインストール

>pip install PyMySQL
>pip list PyMySQL

データベースの作成

事前に接続先データベースを用意する。
mysql> CREATE DATABASE データベース名;

manage.pyの編集

PyMySQLを利用するために、manage.pyに以下のように追記をする。

manage.py
import os
import sys
import pymysql  # 追記

pymysql.install_as_MySQLdb()  # 追記

if __name__ == '__main__':

settings.pyの編集

デフォルトでは、SQLite3の設定が記載されているので、MySQL用に編集する。

(変更前)

settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

(変更後)

settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'データベース名',
        'USER': 'ユーザー名',
        'PASSWORD': 'パスワード',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

マイグレーションを実行

DjangoとMySQLを接続する。

> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... 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 auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying news.0001_initial... OK
  Applying news.0002_auto_20181003_1820... OK
  Applying sessions.0001_initial... OK

テーブルの確認

models.pyに記載したモデルがテーブルに反映されているか確認する。

mysql> USE データベース名;
mysql> SHOW tables;

おわりに

以上は開発環境での接続方法なので、本番環境での設定もメモに残したい。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?