Django makemigrations正常但migrate无响应,数据库列缺失求助
问题解决步骤
问题概述
替换代码后,makemigrations可正常生成迁移文件,但执行migrate时始终提示:
Running migrations: No migrations to apply.
同时运行项目时出现错误:no such column: video_video.about_video。已尝试删除迁移文件、执行flush,问题未解决。
解决方案
1. 彻底重置迁移与数据库(最直接方法)
若数据库无需要保留的数据,按以下步骤操作:
- 删除
video、account等所有应用下migrations文件夹内的所有文件,仅保留__init__.py - 删除项目根目录下的
db.sqlite3数据库文件 - 重新生成初始迁移文件:
python manage.py makemigrations - 应用迁移到数据库:
python manage.py migrate
2. 保留数据库,清理迁移记录
若需保留数据库数据,手动清理Django迁移记录表:
- 进入Django命令行交互环境:
python manage.py shell - 执行代码清理指定应用的迁移记录:
from django.db import connection cursor = connection.cursor() # 清理video应用迁移记录 cursor.execute("DELETE FROM django_migrations WHERE app='video';") # 清理account应用迁移记录 cursor.execute("DELETE FROM django_migrations WHERE app='account';") connection.commit() exit() - 删除本地迁移文件(保留
__init__.py),重新生成并应用迁移:python manage.py makemigrations python manage.py migrate
3. 修复代码错误(避免后续异常)
你的代码存在几处错误,可能导致迁移或运行异常,需修复:
视频应用admin.py
- VideoAdmin类:
search_fields包含不存在的description字段,修改为:search_fields = ('title', 'about_video')prepopulated_field应为复数prepopulated_fields,修改为:prepopulated_fields = {'slug': ('title',)}
- Category的DraggableMPTTAdmin:
prepopulated_field应为复数prepopulated_fields,且关联字段是title而非name,修改为:prepopulated_fields={'slug': ('title',)}
- Comment的DraggableMPTTAdmin:
indented_title对应字段不存在,修改为indented_body:admin.site.register( models.Comment, DraggableMPTTAdmin, list_display=( 'tree_actions', 'indented_body', ), list_display_links=( 'indented_body', ), )
自定义User模型admin.py
fieldsets包含不存在的age字段,删除该字段:fieldsets = ( ('Main', {'fields': ( 'email', 'phone_number', 'fullname', 'bio', 'image', 'password' )}), # 其他内容不变 )
4. 验证迁移结果
执行以下命令确认迁移是否正确应用:
- 查看所有应用的迁移状态:
python manage.py showmigrations - 查看
video应用初始迁移的SQL语句,确认包含about_video字段:python manage.py sqlmigrate video 0001
内容的提问来源于stack exchange,提问作者mobina sattari
相关产品推荐
相关产品推荐

