Django 做migrations时出错,解决方案

在做migrations的时候,偶尔会出现出错。


在已有数据的表中新增字段时,会弹出下面的信息

运行这个命令时

python 复制代码
python manage.py makemigrations

Tracking file by folder pattern: migrations

It is impossible to add a non-nullable field 'example' to book without specifying a default. This is because the database needs something to populate existing rows.

Please select a fix:

  1. Provide a one-off default now (will be set on all existing rows with a null value for this column)
  2. Quit and manually define a default value in models.py.
    Select an option:

解决方案:

选择1

之后会弹出

Please enter the default value as valid Python.

The datetime and django.utils.timezone modules are available, so it is possible to provide e.g. timezone.now as a value.

Type 'exit' to exit this prompt

输入, 必须加双引号

python 复制代码
"1"

migrate 无法生成表

运行这个命令时

python 复制代码
python manage.py migrate

会出现这种结果

python 复制代码
Operations to perform:
  Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.

出现无法生成表的原因是,去到 django_migrations 表里查看,就能知道之前已经创建了表。所以得在该表用sql语句来删除对应的app数据。

最后运行下面两个命令

python 复制代码
python manage.py makemigrations

python manage.py migrate

这样就可以创建表了。


点个赞呗~

相关推荐
小马爱打代码3 小时前
Redis 集群方案详解:主从复制、哨兵、脑裂、分片集群和哈希槽
数据库·redis·哈希算法
海南java第二人4 小时前
ClickHouse 稀疏索引深度解析:为什么 OLAP 数据库不用 B-Tree?
数据库·clickhouse
Litluecat4 小时前
信创迁移:Oracle切换海量数据库,慢sql扫描
数据库·sql·oracle·信创·海量
消失在人海中5 小时前
Oracle的CURRENT REDO丢失,数据丢失风险分析
数据库·oracle
喵了几个咪5 小时前
选择第三方IAM还是自建权限体系?中小型后台系统权限架构决策指南
数据库·oracle·架构
Elastic 中国社区官方博客6 小时前
Kibana:使用 AI Chat 及 MCP 轻松创建 AI 原生仪表板
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·信息可视化
杨云龙UP7 小时前
Oracle Health Check巡检脚本使用SOP V2.0:从HTML原始报告→生成Word专业巡检报告→交付客户_2026-06-03
linux·运维·数据库·sql·oracle·报告·巡检
Database_Cool_7 小时前
Hudi 湖仓一体架构:阿里云 AnalyticDB MySQL 原生集成最佳实践
数据库·mysql·阿里云
我是一颗柠檬7 小时前
【Redis】发布订阅与消息队列Day8(2026年)
数据库·redis·后端·缓存