0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoモデル変更後にOperationalErrorが発生する

0
Posted at

この記事は過去のエラー解決メモを整理したものです。
現在の推奨手順とは異なる可能性があります。
公式ドキュメントを確認して最新情報と差分がないかを確認してください。

事象

Django管理画面で発生したエラーを修正するため、models.pytext = models.TextFieldtext = models.TextField() に変更した。

#models.py
from django.db import models
from django.conf import settings
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField() #ここを修正
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self) -> str:
        return self.title

その後、Django管理サイトを開くと次のエラーが発生した。

#エラーコード
OperationalError at ~models.py
table qs_posts_post has no column named author_id
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py makemigrations
Did you rename post.autor to post.author (a ForeignKey)? [y/N] y
You are trying to add a non-nullable field 'text' to post without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 2
  • You are trying to add a non-nullable field 'text' to post without a default; we can't do that (the database needs something to populate existing rows).
    Please select a fix で検索→migrationを初期化しないとダメっぽい

環境

  • Windows
  • Django 3.2.9
  • Python 3.9.6
  • VSCode 1.62.3

原因

  • モデルの変更をmigrationに反映していなかったため、DBのテーブル定義とDjangoモデルの状態がずれていた。

対策

  • 対象アプリのmigrationを巻き戻し、migrationファイルを作り直してから再度適用する。

手順

(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py showmigrations
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
 [X] 0003_logentry_add_action_flag_choices
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
 [X] 0010_alter_group_name_max_length
 [X] 0011_update_proxy_permissions
 [X] 0012_alter_user_first_name_max_length
blog
 [X] 0001_initial
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py migrate blog zero
Operations to perform:
  Unapply all migrations: blog
Running migrations:
  Rendering model states... DONE
  Unapplying blog.0001_initial... OK
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py showmigrations
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
 [X] 0003_logentry_add_action_flag_choices
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
 [X] 0010_alter_group_name_max_length
 [X] 0011_update_proxy_permissions
 [X] 0012_alter_user_first_name_max_length
blog
 [ ] 0001_initial
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial
  • D:\programs\local_github\test_env\blog\migrations\0001_initialを削除 (物理的に)
  • python manage.py makemigrations
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model Post
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, 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 auth.0012_alter_user_first_name_max_length... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK
  • python manage.py createsuperuser (管理者ユーザーの制作)
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py createsuperuser
ユーザー名 (leave blank to use 'user'): testuser
メールアドレス: xingsantianzhong460@gmail.com
Password: 
Password (again):
Superuser created successfully.
  • python manage.py runserver (サーバー起動)
(test_env-xi-km8kH) D:\programs\local_github\test_env>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
November 23, 2021 - 16:23:01
Django version 3.2.9, using settings 'config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

参考情報

admin管理ページから情報を追加しようとすると no column named|teratail

Djangoでマイグレーションをやり直す

【Django】モデルフィールドを追加・削除した際のmigrate(エラー&成功例)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?