首页 > 解决方案 > django.db.utils.IntegrityError:“地址”列中的空值违反非空约束

问题描述

当我创建一个 Location 实例时,我收到了这个错误。 django.db.utils.IntegrityError: null value in column "address" violates not-null constraint

这是我的定位模型。

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模型所以有None值不address应该抛出这个错误。

标签: pythondjangodjango-modelsdjango-rest-framework

解决方案


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

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

推荐阅读