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

这样就可以创建表了。


点个赞呗~

相关推荐
先吃饱再说10 小时前
存储的进化:从 MySQL 到浏览器缓存,数据到底住在哪?
数据库
Nturmoils10 小时前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
Databend12 小时前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
这个DBA有点耶13 小时前
SQL改写进阶:标量子查询的“隐形代价”与消除实战
数据库·mysql·架构
smallyoung14 小时前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·mysql·postgresql
parade岁月14 小时前
MySQL JOIN解析:朴实无华但食之有味
数据库·后端
用户31693538118314 小时前
MySQL服务无法启动问题解决全记录
数据库
vivo互联网技术18 小时前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
倔强的石头_1 天前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
SelectDB1 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python