Django数据库重新初始化

开发过程中 models.py 中的模型经历一番爆改后,执行migrate就报错。干脆重新初始化。

操作步骤:

  1. 删除旧的数据库文件,重新创建。如果你是使用SQLite,删除后无需重新创建,Django在运行迁移时可以自动完成SQLite数据库创建。如果使用其他数据库,需要手动创建一个新的数据库。

  2. 删除迁移文件 :删除每个应用下的migrations文件夹中除了__init__.py文件以外的所有文件。这一步是为了清除Django对旧数据库结构的迁移记录。

    复制代码
    import os
    
    exclude = ["venv"] # 需要排除的文件目录
    for root, dirs, files in os.walk('.'):
        dirs[:] = [d for d in set(dirs) - set(exclude)]
        if 'migrations' in dirs:
            dir = dirs[dirs.index('migrations')]
            for root_a, dirs_a, files_a in os.walk(os.path.join(root, dir)):
                for file_b in files_a:
                    if file_b != '__init__.py':
                        dst_file = os.path.join(root_a, file_b)
                        print('删除文件>>> ', dst_file)
                        os.remove(dst_file)
  3. 执行 重建数据库并初始化的命令:

    复制代码
    # 依次执行
    python manage.py flush 
    python manage.py makemigrations
    python manage.py migrate
相关推荐
金銀銅鐵2 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup112 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf2 天前
Agent 流程编排
后端·python·agent
copyer_xyf2 天前
Agent RAG
后端·python·agent
copyer_xyf2 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf2 天前
Agent 记忆管理
后端·python·agent
星云穿梭3 天前
用Python写一个带图形界面的学生管理系统——完整教程
python