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

这样就可以创建表了。


点个赞呗~

相关推荐
SelectDB9 分钟前
Apache Doris AI 能力揭秘(三):AI_AGG 与 EMBED 函数深度解析
数据库·后端·apache
普通网友10 分钟前
用Python批量处理Excel和CSV文件
jvm·数据库·python
y***613113 分钟前
在Spring Boot项目中使用MySQL数据库
数据库·spring boot·mysql
ApacheSeaTunnel15 分钟前
(四)收官篇!从分层架构到数据湖仓架构系列:数据服务层和数据应用层及湖仓技术趋势小结
数据库·开源·数据湖·技术分享·白鲸开源
艾斯比的日常18 分钟前
MySQL 锁机制深度解析:从原理到实践
数据库·mysql
linuxxx11019 分钟前
高考志愿填报辅助系统
redis·后端·python·mysql·ai·django·高考
Starduster40 分钟前
一次数据库权限小改动,如何拖垮半个互联网?——Cloudflare 2025-11-18 大故障复盘
数据库·后端·架构
一 乐1 小时前
宠物猫店管理|宠物店管理|基于Java+vue的宠物猫店管理管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·宠物管理
w***37511 小时前
【SQL技术】不同数据库引擎 SQL 优化方案剖析
数据库·sql
一 乐1 小时前
考公|考务考试|基于SprinBoot+vue的考公在线考试系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·课程设计