DjangoでMySQLに接続と設定する手順を紹介

Django開発でmysqlに接続と設定する手順を1から紹介します。

昨今はDockerにMySqlの環境構築が当たり前、みたいな風潮というかそれがスタンダードになりつつありますがまた別の機会に紹介をしたいと思います。

今回のゴールは最終的に、djangoのsettings.pyを設定して、djangoを立ち上げ(runserver)してもエラーが出ることなく使用できるまでになります。

環境

環境

・Mac BigSur 11.3

・python 3.8

・django 2.2

・homebrewをインストール済み

homebrewをまだインストールしていない人は以下より参照ください。

MySQLのインストール

まずはインストールするためにターミナルを開きます。

そして以下のインストールコマンドを入力します。

バージョンを指定せずに以下のようにインストールすると最新版のMySQLがインストールされます。

$ brew install mysql

今回はバージョン5.7をインストールするためにバージョンを指定してインストールを実行します。

% brew install mysql@5.7
==> Downloading https://ghcr.io/v2/homebrew/core/mysql/5.7/manifests/5.7.34
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/mysql/5.7/blobs/sha256:baf50315
==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh
######################################################################## 100.0%
==> Pouring mysql@5.7--5.7.34.big_sur.bottle.tar.gz
==> /usr/local/Cellar/mysql@5.7/5.7.34/bin/mysqld --initialize-insecure --user=sample --basedir=/usr/local/Cellar/mysql@5.7/5.
==> Caveats
We've installed your MySQL database without a root password. To secure it run:
    mysql_secure_installation

MySQL is configured to only allow connections from localhost by default

To connect run:
    mysql -uroot

mysql@5.7 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.

If you need to have mysql@5.7 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/mysql@5.7/bin:$PATH"' >> ~/.zshrc

For compilers to find mysql@5.7 you may need to set:
  export LDFLAGS="-L/usr/local/opt/mysql@5.7/lib"
  export CPPFLAGS="-I/usr/local/opt/mysql@5.7/include"


To have launchd start mysql@5.7 now and restart at login:
  brew services start mysql@5.7
Or, if you don't want/need a background service you can just run:
  /usr/local/opt/mysql@5.7/bin/mysql.server start
==> Summary
🍺  /usr/local/Cellar/mysql@5.7/5.7.34: 319 files, 234.7MB

問題なくインストールされれば以上の画面になります。

パスを通す

インストールが完了したら次はパスを通します。

先述したMySQLインストール画面中に

If you need to have mysql@5.7 first in your PATH, run:
echo ‘export PATH=”/usr/local/opt/mysql@5.7/bin:$PATH”‘ >> ~/.zshrc

というメッセージが親切に表示されていますのでそちらを利用します。

ホーム画面に.zshrcがない人は.zshrcファイルを作成します。

% cd
% touch .zshrc
% vim .zshrc

.zshrcのファイルに先ほどインストール時に出現したコマンドを入力します。

 ~ % cat .zshrc
export PATH="/usr/local/opt/mysql@5.7/bin:$PATH"

mysqlのバージョンを以下のコマンドで確認します。

% mysql --version
mysql  Ver 14.14 Distrib 5.7.34, for osx10.16 (x86_64) using  EditLine wrapper

このようにコマンドが返ってこればきちんとpathが通っていることになります。

仮に、mysql –versionと入力してもcommand not foundのようなメッセージが返ってくる場合は、一度ターミナルを再起動させてから実行してみるとうまくいきます。

MySQLを起動

MySQLを使用するには、MySQLを起動させる必要があります。

以下のコマンドでhomebrewにインストールされたMySQLを起動させます。

% brew services start mysql@5.7
==> Tapping homebrew/services
Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-services'...
remote: Enumerating objects: 1224, done.
remote: Counting objects: 100% (103/103), done.
remote: Compressing objects: 100% (83/83), done.
remote: Total 1224 (delta 38), reused 46 (delta 19), pack-reused 1121
Receiving objects: 100% (1224/1224), 361.89 KiB | 11.67 MiB/s, done.
Resolving deltas: 100% (515/515), done.
Tapped 1 command (28 files, 437.4KB).
==> Successfully started `mysql@5.7` (label: homebrew.mxcl.mysql@5.7)

Successfullyというメッセージで起動は確認できました。

起動は以下のコマンドでも確認できます。

% mysql.server status
 SUCCESS! MySQL running (29008)

ログインする

mysqlにインストール後に初めてrootユーザーでログインする時は、パスワードは設定されていません。

なので以下のように、Enter password:を求められた時は何も入力せずに、Enterキーをおします。

% mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.34 Homebrew

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

パスワードの設定方法に関しては以下で紹介しています。

データベースの作成

データベース名をsampleとしてデータベースを以下のコマンで作成します。

mysql> create database sample;
Query OK, 1 row affected (0.01 sec)

またデータベース一覧の確認は以下のコマンドで実行します。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| sample           |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

これでMySQL側の準備は完了しました。

mysqlclientのインストールをする

MySQLとDjangoを接続するために必要な、mysqlclientライブラリをインストールします。

% brew install mysqlclient

settings.pyにMySQLを設定する

初期状態では以下のようになっています。

settings.py

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

これを先ほど設定したmysqlの設定に合わせます。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foodtech',
        'USER': 'root',
        'PASSWORD': '',
    }
}

起動させて確認

この状態で、djangoを起動させて問題ないかを確認します。

% python manage.py runserver

起動させても何もエラーが出なければきちんとmysqlと接続ができていることになります。

またdjangoをインストールしてからデータベースを何も操作していない場合は、このような文言が出現していると思います。

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

シンプルにコマンドを実行してあげます。

 % 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 auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

これは内部的なデータベースが作成されたことを意味します。

以上になります。

最後に

いかがでしたでしょうか。

以上が、「DjangoでMySQLに接続と設定する手順を紹介」の紹介記事になります。

プログラミング学習を効率良く進めるには…

私ヒロヤンがプログラミングを始めた頃は以下のような感じでした。

何から手をつけていいのか、わからない。

プログラミングを始めてみたけど、エラーが解決できない。

そしてネットで調べていくうちに膨大な時間が過ぎていきました。

私ヒロヤンの実体験より、プログラミングを効率的に学ぶために大切なことは以下のことだと考えています。

1. いつまでもダラダラとやらないで、目標を決定して短期集中する

2. マンツーマンで、わからない箇所は直ぐに質問をして即レスをもらう

.proでは私ヒロヤンが学習してきたプログラミング経験0からのpython/django、その他webサイト・サービス開発のコースが用意されています。

カウンセリング自体は無料なので話を聞いてみるだけでもいかがでしょうか?

また以下のリンク先ではdjangoを教えてくれるスクールをまとめ紹介しています。

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です