LoginSignup
12
17

More than 1 year has passed since last update.

Django で MariaDB を使う

Last updated at Posted at 2018-12-10

Dejango のディフォールトのデータベースは sqlite3 ですがそれを MariaDB に切り替える方法です。

MariaDB が動作していることを確認

sudo systemctl status mariadb

python の mysqlclient をインストール

Arch Linux では

sudo pacman -S python-mysqlclient

Ubuntu では

sudo pip3 install  mysqlclient

次のライブラリーが必要です。

sudo apt install libmariadb-dev-compat libmariadb-dev

MariaDB に
user: django
password: tiger123
データベース: django
を作成

MariaDB [(none)]> create user 'django'@'localhost' identified by 'tiger123';
Query OK, 0 rows affected (0.046 sec)

MariaDB [(none)]> create schema django;
Query OK, 1 row affected (0.001 sec)

MariaDB [(none)]> grant all on django.* to 'django'@'localhost';
Query OK, 0 rows affected (0.013 sec)

確認方法

mysql -udjango -ptiger123 django

proj01 というプロジェクトがあるとして、
proj01/settings.py を編集

proj01/settings.py
省略
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'django',
        'PASSWORD': 'tiger123',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
                },
    }
}
省略

設定の変更を反映する

python manage.py migrate

データベースを使ってみる

$ python manage.py dbshell
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 43
Server version: 10.5.12-MariaDB-1build1 Ubuntu 21.10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [django]>

スーパーユーザーの作成

python manage.py createsuperuser

パスワードなどを入力
メールアドレスは、test@test.com で可。

開発サーバーを起動

python manage.py runserver

ブラウザーで http://127.0.0.1:8000/admin/ にアクセス
admin.png

ログインしてユーザーなどを作成
user.png

MariaDB には次のテーブルが作成されています。

MariaDB [django]> show tables;
+----------------------------+
| Tables_in_django           |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+

次のバージョンで確認しました。

$ python --version
Python 3.8.5
$ python -m django --version
3.1.1
12
17
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
12
17