删除Django模型属性后仍触发django.db.utils.IntegrityError: UNIQUE constraint failed错误的解决请求
Got it, let's walk through how to resolve this issue completely. The problem stems from a mismatched state between your Django model, migration files, and database—even though you removed the desc field from your Post model, the migration that tried to add it is still causing conflicts. Here's what to do:
Step 1: Check and Clean Up Migration Status in the Database
Django tracks applied migrations in the django_migrations table. First, we need to make sure the failed migration isn't incorrectly marked as applied:
- Open a Django shell to query the migration status:
py manage.py shell - Run these lines to check if the problematic migration is in the table:
from django.db import connections cursor = connections['default'].cursor() cursor.execute("SELECT * FROM django_migrations WHERE app='blog' AND name='0004_post_desc'") print(cursor.fetchall()) - If you get a result (meaning the migration is marked as applied), delete that record to reset the state:
Exit the shell withcursor.execute("DELETE FROM django_migrations WHERE app='blog' AND name='0004_post_desc'")exit()when done.
Step 2: Delete the Problematic Migration File
Head to your blog app's migrations folder, and delete these two files (if they exist):
0004_post_desc.py0004_post_desc.pyc(compiled Python file, might not be present)
Step 3: Remove the Leftover desc Column from the Database
If the migration partially applied, your blog_post table might still have the desc column. Let's delete it:
- Reopen the Django shell:
py manage.py shell - Execute this SQL command to drop the column (works for SQLite 3.35.0+—most modern environments meet this requirement):
If you're on an older SQLite version, you'll need to create a new table, migrate data over, delete the old table, and rename the new one—but this is rarely necessary these days.from django.db import connections cursor = connections['default'].cursor() cursor.execute("ALTER TABLE blog_post DROP COLUMN desc;")
Step 4: Sync Migrations with Your Model
Now your model, migration files, and database should be aligned. Run these commands to confirm:
py manage.py makemigrations py manage.py migrate
You should see a message saying "No changes detected" for makemigrations, and migrate will confirm everything is up to date.
Why This Happened
When you added the desc field with unique=True and tried to migrate, Django attempted to add this field to all existing Post records. If you didn't set a unique default value (or used a default like an empty string), all existing records would have the same desc value—violating the unique constraint and causing the migration to fail. Even after removing the field from your model, the orphaned migration file and messed-up migration state kept triggering the error.
内容的提问来源于stack exchange,提问作者Destiny Kefas

