Search code examples
djangodjango-modelsslugdjango-migrations

slug error still comes after deleting django model


I had created a model in models.py but forgot to add the slug field. The error Key (slug)=() is duplicated comes after python manage.py migrate command. So I deleted my model and the slug field and again run the migration command but still the python manage.py migrate command shows the same error. I cannot delete my whole database because I have data stored in other models also. Here is the output of python manage.py showmigrations command:

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
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
schooldekho
[X] 0001_initial
[X] 0002_auto_20181114_0012
[X] 0003_auto_20181114_0041
[X] 0004_auto_20181114_0043
[X] 0005_auto_20181116_1759
[X] 0006_school
[ ] 0007_school_slug
[ ] 0008_auto_20181116_2259
[ ] 0009_auto_20181116_2300
[ ] 0010_auto_20181116_2304
[ ] 0011_remove_school_slug
[ ] 0012_auto_20181118_2238
sessions
[X] 0001_initial

All I want is to run the migration successfully without any error.


Solution

  • You need to create a migration which will add the SlugField with null=True and with no default specified for default=None. Then create an empty migration, and modify it so that you will populate the slug field that was added in the previous migration. Then you can create a new migration that will remove the null=True constraint.

    Short version:

    1. Create nullable column
    2. Populate all null values for column via data migration.
    3. Make column not-nullable.