Django迁移异常求助:django_admin_log已存在等问题
Hey there, let's work through these annoying Django migration issues step by step—they're super common when your migration records and database state get out of sync, so you're not alone here!
Let's tackle the "relation 'django_admin_log' already exists" error first
This happens when your database already has the django_admin_log table, but Django's migration tracking (the django_migrations table in your DB) doesn't have the admin app's migrations marked as applied. Here's how to fix it:
First, check which admin migrations are supposed to be applied. Run this to see the initial admin migration details:
python manage.py sqlmigrate admin 0001You'll see the SQL that creates
django_admin_logand other admin-related tables—confirm this matches what's already in your database.Since the table already exists, we just need to tell Django to mark this migration as applied without re-running the SQL. Use the
--fakeflag:python manage.py migrate --fake admin 0001If there are later admin migrations (like
0002), repeat this command with the latest migration number for the admin app.Verify it worked by running
python manage.py migrateagain—this error should disappear now.
Next: "no changes detected" when running makemigrations
Quick check: I think you meant python manage.py makemigrations (not run migrations). If you're seeing this message even after modifying your models, try these fixes:
- Double-check that you saved your
models.pyfile—yes, it sounds obvious, but we've all forgotten this step! - Confirm your app is listed in
INSTALLED_APPSinsettings.py—Django won't track models from unregistered apps. - If you're working on a newer project and haven't made actual model changes, this message is normal! But if you did modify something, try deleting all files in your app's
migrationsfolder except__init__.py, then re-runmakemigrations. Note: Only do this for development projects—never delete migrations in production!
Finally: Unapplied migration warnings when running runserver
This warning pops up because Django thinks there are migrations that haven't been applied to your database. Once you fix the first two issues, this should resolve itself, but if it doesn't:
- Run
python manage.py showmigrationsto see which migrations are marked as unapplied (look for entries without[X]next to them). - For migrations that correspond to tables you already have in your DB, use
migrate --faketo mark them as applied (like we did with the admin migration). - For migrations that you actually need to apply (new models/fields you added), run
python manage.py migratenormally to apply them.
Important Notes
- Always back up your database before messing with migrations, especially in production.
- The
--fakeflag only updates Django's migration tracking—it doesn't modify your database, so use it only when you're sure the database already matches the migration's state.
内容的提问来源于stack exchange,提问作者Shoaib Iqbal

