python - django.db.utils.IntegrityError : null value in column "address" violates not-null constraint

标签 python django django-models django-rest-framework

当我创建一个 Location 实例时,我得到了这个错误。 django.db.utils.IntegrityError: "address"列中的空值违反非空约束

这是我的定位模型。

class Location(DirtyFieldsMixin, TimeStampedModel):

    id = SmallUUIDField(
        default=uuid_default(),
        primary_key=True,
        db_index=True,
        editable=False,
        verbose_name='ID'
    )
    name = models.CharField(max_length=100)
    address = models.TextField(blank=True)
    timezone = models.CharField(null=True, max_length=100)
    phone = PhoneNumberField(blank=True)
    email = models.EmailField(blank=True)

发布位置时,有效负载看起来像这样。

{'name': 'Beij the Sage', 'address': None, 'latlon': None, 'timezone': 'America/Los_Angeles', 'phone': '', 'email': ''}

我为模型设置了 blank=True,因此将 address 的值设置为 None 不应引发此错误。

最佳答案

blank=True 仅控制表单级验证。您在数据库验证层遇到错误,因为该字段默认为 null=False。要保存空值,您必须将 null=True 添加到构造函数 kwargs。

address = models.TextField(blank=True, null=True)

关于python - django.db.utils.IntegrityError : null value in column "address" violates not-null constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56139607/

相关文章:

python - 我想根据特定的单词来划分文件,并且根据这个单词我想要上面的行,然后放入newfile.txt

python - timeit 结果中运行次数和循环次数之间的差异

django - 无法在 Ubuntu 13.10 上安装 pylibmc(使用 Python 3.3.2)

python - django:为可以是作家或 Actor 或两者的人创建模型

Django 在创建时为对象设置创建者/所有者

python - 每个变量的堆栈和返回值计数?

python - Django TestCase 不在辅助数据库上使用事务

python - Pipenv (django) 中的 .env 文件 - ValueError : embedded null character

Django:如何从管理器内部访问模型的实例?

Python:捕获logging.exception()调用