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

这样就可以创建表了。


点个赞呗~

相关推荐
薛定谔的算法16 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend17 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术18 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
c8i1 天前
drf初步梳理
python·django
Raymond运维1 天前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉1 天前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud2 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud2 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence2 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
c8i2 天前
django中的FBV 和 CBV
python·django