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

这样就可以创建表了。


点个赞呗~

相关推荐
思成不止于此1 小时前
【MySQL 零基础入门】DDL 核心语法全解析:数据库与表结构操作篇
数据库·笔记·学习·mysql
aspirestro三水哥1 小时前
2.5构建Xenomai测试与演示镜像
数据库·rtos·xenomai
随机昵称_1234562 小时前
postgresql连接报错Invalid SCRAM client initialization
数据库·postgresql
Fuly10242 小时前
langchain基础教程(6)---构建知识库--②向量数据库-milvus
数据库·langchain·milvus
TDengine (老段)2 小时前
TDengine IDMP 产品路线图
大数据·数据库·人工智能·ai·时序数据库·tdengine·涛思数据
计算机学姐4 小时前
基于Python的商场停车管理系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·flask
刺客xs4 小时前
MySQL数据库----通配符,正则表达式
数据库·mysql·正则表达式
无限大.4 小时前
计算机十万个为什么--数据库索引
数据库·oracle
思成不止于此4 小时前
MySQL 数据操作:增删改核心语法全解析
数据库·笔记·学习·mysql
得物技术4 小时前
数据库AI方向探索-MCP原理解析&DB方向实战|得物技术
数据库