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
相关推荐
FishCoderh12 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅12 小时前
Python函数入门详解(定义+调用+参数)
python
李广坤12 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
曲幽13 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时17 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿19 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python