2
2

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 3 years have passed since last update.

DjangoでMySQLに接続(Docekrコンテナ別)

Last updated at Posted at 2021-02-02

#◆djagnoでデータベースの接続先をsqlite3からMySQLに変更
dockerでpythonコンテナとデータベースコンテナを分けています。
データベースコンテナにはMySQLをインストールしています。

データベースの接続先をMySQLに変更する際に触った設定について記載します。

#◆データベースコンテナに入る

$ winpty docker-compose exec db bash

#◆データベースに接続

/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 23
Server version: 5.7.32 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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.

mysql>

#◆データベースを確認

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.04 sec)

djangoに接続するデータベースがないことを確認しました。

#◆pythonコンテナに入る

$ winpty docker-compose exec python bash

#◆djangoのsettings.pyの中身

DATABASES = {
    'default': {
		'ENGINE': 'django.db.backends.mysql',
		'NAME': 'mysql',
		'USER': '------',
		'PASSWORD': '-----',
		'HOST': '-----',
		'PORT': '-----',

#◆pymysqlをインストール

pip install pymysql

#◆djangoアプリのmanage.pyの中身
以下を追記しました。

import pymysql
pymysql.install_as_MySQLdb()

#◆データベースにテーブルを追加

python manage.py migrate

#◆データベースにテーブルができているかを確認

mysqlコンテナに入り、データベースに接続します。
その後、以下を入力します。

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_mysql            |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| board_board                |
| columns_priv               |
| db                         |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| engine_cost                |
| event                      |
| func                       |
| general_log                |
| gtid_executed              |
| help_category              |
| help_keyword               |
| help_relation              |
| help_topic                 |
| innodb_index_stats         |
| innodb_table_stats         |
| ndb_binlog_index           |
| plugin                     |
| proc                       |
| procs_priv                 |
| proxies_priv               |
| server_cost                |
| servers                    |
| slave_master_info          |
| slave_relay_log_info       |
| slave_worker_info          |
| slow_log                   |
| tables_priv                |
| time_zone                  |
| time_zone_leap_second      |
| time_zone_name             |
| time_zone_transition       |
| time_zone_transition_type  |
| user                       |
+----------------------------+

テーブルが作成されていることを確認しました。

#◆テーブルを作成する
djangoのmodels.pyに以下を記載し、テーブルを作成します。

from django.db import models

# Create your models here.

class Users(models.Model):
    name = models.CharField(max_length=255)
    kana = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    tel = models.CharField(max_length=13, null=True)
    password = models.CharField(max_length=255, null=True)
    created_at = models.DateTimeField()
    updated_at = models.DateTimeField(null=True)

    class Meta:
        db_table = "users"

#◆テーブルにデータを格納する
以下のjsonファイルを用意します。

[
  {
    "model": "board.Users",
    "pk": 1,
    "fields": {
      "name": "テスト",
      "kana": "てすと",
      "email": "test@gmail.com",
      "tel": "09000000000",
      "password": "11111111",
      "created_at": "2020-01-01T10:00:00.000"
    }
  }
]

以下のコマンドでテーブルにjsonファイルに記載したデータを格納します。

 python manage.py loaddata board/fixtures/users.json

#◆データを確認する

# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 45
Server version: 5.7.32 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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.

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_mysql            |
+----------------------------+
| ~~~~~~~~~~~~~~             |
| time_zone_transition       |
| time_zone_transition_type  |
| user                       |
| users                      |
+----------------------------+
47 rows in set (0.00 sec)

mysql> describe users;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | NO   |     | NULL    |                |
| kana       | varchar(255) | NO   |     | NULL    |                |
| email      | varchar(255) | NO   |     | NULL    |                |
| tel        | varchar(13)  | YES  |     | NULL    |                |
| password   | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime(6)  | NO   |     | NULL    |                |
| updated_at | datetime(6)  | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> select * from users;
+----+------+------+----------------+-------------+----------+----------------------------+------------+
| id | name | kana | email          | tel         | password | created_at                 | updated_at |
+----+------+------+----------------+-------------+----------+----------------------------+------------+
|  1 | ???  | ???  | test@gmail.com | 09000000000 | 11111111 | 2020-01-01 01:00:00.000000 | NULL       |
+----+------+------+----------------+-------------+----------+----------------------------+------------+
1 row in set (0.03 sec)

データが格納されていることが確認できました。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?