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 小时前
2026年数据库国产化替代性能调优方法论:从SQL基线建立到持续优化的全流程体系
数据库·sql
你有我备注吗3 小时前
SQL之数据更新
数据库·sql
跨境技工小黎3 小时前
动态住宅代理使用指南:粘性会话 vs. 每次请求轮换 IP,如何选择?
数据库
AAA@峥5 小时前
系统化学习 MySQL:数据类型、库表管理、增删改查全解析
数据库·学习·mysql
流星白龙12 小时前
【Redis】2.Redis重大版本
数据库·redis·junit
流星白龙12 小时前
【Redis】7.Hash表
数据库·redis·哈希算法
流星白龙13 小时前
【Redis】4.基本全局命令
数据库·redis·缓存
王八八。14 小时前
Navicat 17破解版下载安装教程 附安装激活步骤(2026 最新版)
数据库·navicat
Jelena1577958579214 小时前
电商运营分析数据比价接口实战:多平台价格监控与智能决策系统
java·大数据·数据库
流星白龙16 小时前
【Redis】3.Redis安装与命令行客户端
数据库·redis·缓存