LoginSignup
10
11

More than 3 years have passed since last update.

MySQLの既存テーブルをDjangoで扱うときのメモ

Posted at

1.準備

まずはsettings.pyにMySQLの接続先情報を記述します。

settings.py
import pymysql
pymysql.install_as_MySQLdb()
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '###db',  # データベース名
        'USER': 'root',  # ユーザ名
        'PASSWORD': 'password',  # パスワード
        'HOST': '127.0.0.1',  # MariaDBがあるサーバのIPアドレスやホストを。空欄はローカルホスト
        'PORT': '3306',  # 空欄はデフォルトポートの3306
    }
}

MySQLを扱うモジュールが必要なため、PYMYSQLをインストールしてきます。

pip install PyMySQL

2.マイグレートしていく

Models.pyに記載するモデル定義情報を自動で生成

下記コマンドで既存テーブルのモデル定義を自動で作ります。
python manage.py inspectdb table テーブル名

> python manage.py inspectdb table テーブル名
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
# Unable to inspect table 'table'
# The error was: (1146, "Table '##db.table' doesn't exist")


class Usertable(models.Model):
    id = models.BigIntegerField(unique=True, blank=True, null=True)
    name = models.CharField(max_length=50, blank=True, null=True)
    screen_name = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    profile_image_url = models.TextField(blank=True, null=True)
    follow_count = models.IntegerField(blank=True, null=True)
    followers_count = models.IntegerField(blank=True, null=True)
    tweet_count = models.IntegerField(blank=True, null=True)
    video_count = models.IntegerField(blank=True, null=True)
    video_count_date = models.BigIntegerField(blank=True, null=True)
    image_count = models.IntegerField(blank=True, null=True)
    image_count_date = models.BigIntegerField(blank=True, null=True)
    twitter_created_at = models.DateTimeField()
    created_at = models.DateTimeField()
    updated_at = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'usertable'

出力された情報はプロジェクトのmodels.pyにコピー&ペーストにしましょう。
ちなみに上記コマンドを事項した際にエラーらしきものが確認できる。
# The error was: (1146, "Table '##db.table' doesn't exist")
これは何なのか、正直わからないw教えていただきたい。

マイグレートしたらエラーでた('id' can only be used as a field name if the field also sets 'primary_key=True')

> python manage.py migrate
SystemCheckError: System check identified some issues:

ERRORS:
hello.Usertable: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'.

翻訳したらわかるように
'id'は、フィールドに 'primary_key = True'も設定されている場合にのみフィールド名として使用できます。
既存テーブルにidカラムがある場合は制限があるようです。

先ほどのmodels.pyのidの定義を下記に変更しました。

id = models.BigIntegerField(unique=True, blank=True, null=True, primary_key=True)

再度実行してみます。
またエラー。。。null=Teueはいらないようです。

> python manage.py migrate
SystemCheckError: System check identified some issues:

ERRORS:
hello.Usertable.id: (fields.E007) Primary keys must not have null=True.
        HINT: Set null=False on the field, or remove primary_key=True argument.

再度直して。

id = models.BigIntegerField(unique=True, blank=True, primary_key=True)

> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

ん?なにかおかしい。
そもそも私の理解が足りず、まずはマイグレーションをしてほしいみたい。
下記の感じかな!?

・まずは、マイグレーションで移行する情報をまとめるマイグレーションファイルを作成.

> python manage.py makemigrations
Migrations for 'hello':
  hello\migrations\0001_initial.py
    - Create model Usertable

・マイグレーションファイルの適用.

> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, hello, sessions
Running migrations:
  Applying hello.0001_initial... OK

管理サイトからもアクセスできるように。

下記にアクセスすれば管理サイトにアクセスできるかと思いますが、管理サイトからテーブル情報を操作できます。
http://127.0.0.1:8000/admin/

そのままでは表示もされないので、管理サイトでデータベースを確認できるようにします。
作ったアプリの配下にあるadmin.pyを編集します。

from django.contrib import admin
from hello.models import Usertable #追加

# Register your models here.
admin.site.register(Usertable) #追加

Models.pyのモデル定義をした際の
class Usertable(models.Model):
クラス名をimport&registerしています。

10
11
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
10
11