Django 的文档非常清楚在数据库级别将空字符串存储为 ""而不是 NULL(因此空数据只有一种可能的格式):
Note that empty string values will always get stored as empty strings, not as NULL. Only use null=True for non-string fields such as integers, booleans and dates. For both types of fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).
尽管如此,在添加新字段后,我开始在新字段 (phone_number) 上遇到 IntegrityErrors。
null value in column "phone_number" violates non-null constraint
该模型在新字段中看起来像这样(我通过南执行了迁移):
class Person(models.Model):
user = models.ForeignKey(User)
description = models.TextField(blank=True)
phone_number = models.CharField(blank=True)
我已经(暂时)通过在 phone_number 上设置 null=True 解决了这个问题,但现在我有数百个空字符串条目,并且我的数据库中有一个 NULL 值。 (我也尝试将 default='' 添加到 phone_number 字段,但我仍然看到 IntegrityError 问题。)
过去我一直使用 MySQL,但在这个项目中我使用 Postgres。生成的 SQL 插入尝试是:
'INSERT INTO "people_person" ("user_id", "description", "gender", "birthdate", "default_image_id", "zip_code", "beta_status") VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING "people_person"."id"'
.我的期望是 Django 会在“phone_number”列中插入一个空白字符串,但它似乎没有这样做。我可能期望的另一件事是 Django 在 CREATE TABLE 语句中包含一个 SET DEFAULT,但它没有。所以 Postgres 对那个列上的 NOT NULL 很生气。
谢谢!
最佳答案
与通常看似难以解决的问题一样,手头的问题是用户错误。
我的应用程序有两个入口点——两个 WSGI 文件,但只有一个代码库。通常,Apache 只会在文件被触及时重新加载您的代码。我的部署脚本只涉及那些 WSGI 文件中的一个 - 这意味着通过另一个 WSGI 文件访问我的站点的人仍然看到旧代码。更糟糕的是,数据库在旧代码下进行了修改,但模型仍然和以前一样。
这反过来导致了 IntegrityError
问题。 Django 不知道 phone_number
字段,所以即使我设置了 blank=True
, Django 没有尝试插入空白值 - 数据库当然认为这意味着 NULL。
这导致了一系列不同的追踪错误,包括上述错误。
令人惊讶的是,像这样的真正棘手的问题经常是由愚蠢的小遗漏引起的 - 就像我 2 个月前写的部署脚本,忘记更新了。
感谢阅读人们,我已经赞成其他答案,但我需要接受我的,因为它最终是解决方案。
关于Django ORM、CharField 和空白=真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7111590/