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

这样就可以创建表了。


点个赞呗~

相关推荐
会编程的土豆8 分钟前
GORM 常见操作从入门到能写 DAO
数据库·gorm
A153625534 分钟前
2026 电商物流系统推荐:多渠道仓配履约数字化选型指南
大数据·数据库·人工智能
ClouGence2 小时前
CloudDM:开源免费!一站式数据库访问、SQL审核、权限与脱敏管控平台
数据库·sql·开源
(轻舟已过万重山)2 小时前
第39章 评估迭代:上线只是开始,迭代才是关键
大数据·数据库·人工智能
oradh2 小时前
Oracle参数文件(PFILE与SPFILE)维护操作总结
数据库·oracle·oracle参数·spfile·pfile
l1t3 小时前
kryonix提交的DuckDB 统一并优化标量执行器基础设施 - #24564 PR
开发语言·数据库·数据仓库·sql
鸽芷咕3 小时前
【金仓数据库征文】从 Oracle 到金仓:一次零误差的数据库国产化迁移实录
数据库·oracle
0566464 小时前
RAG 向量检索:从“查字“到“查意“
数据库·人工智能·学习·oracle
bug嘛我经常写4 小时前
dbf文件UTF-8转GBK编码,以及两编码文件互转
数据库·python
知行合一。。。4 小时前
LangGraph--03--本地服务与 Studio 调试
数据库