python - django 要求添加默认值

标签 python django python-3.x

我是 django 的新手,我遇到了一些问题。

这是我以前的模型。

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

我向这个模型添加了一些数据。 之后,我又添加了一个字段。 现在我的模型看起来像这样..

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()
    age = models.IntegerField()

当我运行命令 python manage.py makemigrations 时,我收到了以下明显的错误。

You are trying to add a non-nullable field 'age' to blog without a default; we can't do that (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 let me add a default in models.py
Select an option:

我不想添加 default 所以我通过访问 db.sqlite3 删除 表内容

但是在运行 python manage.py makemigrations 之后我又遇到了同样的错误。为什么?

最佳答案

即使您删除了表,对 Django 模型的任何更改都将始终引用该模型的先前迁移,因此它仍然需要您设置默认值。如果您仍在开发中,那么您可以删除该模型的迁移,然后再次进行迁移。但是,这是一种糟糕的做法,除非你有意识地压缩你的模型,否则你不应该这样做,更好的方法是按照 Django 告诉你的去做并设置一个默认值。从长远来看,这将有助于错误处理。

其他答案解决了如何很好地设置默认值。

关于python - django 要求添加默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54496092/

相关文章:

python - Pandas Groupby 与 Agg Min/Max 日期

python - 在 Pygame 中正确旋转 Cannon 的问题仍然存在

python - 在 python 脚本中生成包含图像和文本的 html 文档(如果可能,无需服务器)

python - 没有 sys 或 os 的相对导入校正

python - 在 poke 游戏的技巧中迭代元组时更新 defaultdict

python - PyTorch 张量 - 使用给定的结束索引列表进行矢量化切片

python - 基于某些 if 并涉及行操作创建新的 pandas 列

python - 什么是 django.test.client 等效于测试外部 URL 提取的服务器?

python - Django:从另一个应用程序导入 View

python - 如何在 argparse 中将子解析器设置为可选?