Django
アプリの作成の途中(たぶんマイグレーション済み?)で、 ベーシックユーザーからカスタムユーザーに変更すると、マイグレーションに失敗します。
bash$ python manage.py makemigrationsdjango.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency user.0001_initial on database 'default'.
対処法
admin
に関する部分をコメントアウトします。
config/settings.py
pythonINSTALLED_APPS = [# 'django.contrib.admin',...]
config/urls.py
pythonurlpatterns = [# path('admin/', admin.site.urls),...]
この状態でマイグレーションしてあげます。
bash$ python manage.py migrateOperations to perform:Apply all migrations: auth, contenttypes, sessions, userRunning migrations:Applying user.0001_initial... OK
上手くいきます。
あとはコメントアウトを解いてあげます。
swappable オプションを使う
以上で解決できない場合は、
公式ドキュメントの Customizing authentication in Django # Changing to a custom user model mid-project | Django documentation | Django が参考になるかもしれません。
titleclass User(AbstractBaseUser, PermissionsMixin):class Meta:swappable = 'AUTH_USER_MODEL'# ...
class Meta
に、 swappable
オプションをしてマイグレーションします。
bash$ dj migrateSystemCheckError: System check identified some issues:ERRORS:app.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'.HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'.auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'.HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'.# swappable 指定後$ dj migrateOperations to perform:Apply all migrations: admin, app, auth, contenttypes, sessionsRunning migrations:Applying app.0002_user... OK
上手くいきます。
そもそも起きないようにする
公式ドキュメントでは、
If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you.
てな感じで、そもそも初期段階でユーザーモデルを差し替えちゃいなさいと言ってるので、 なにより先にユーザーモデルをカスタムユーザーに差し替えておくのが良さそうです。