【问题标题】:django.db.utils.IntegrityError: null value in column "address" violates not-null constraintdjango.db.utils.IntegrityError:“地址”列中的空值违反非空约束
【发布时间】:2019-05-14 22:49:00
【问题描述】:

当我创建一个 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 不应该抛出这个错误。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 记得在更新模型后重新运行 make migrations :)
    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 2021-12-06
    • 2016-04-04
    • 2021-11-02
    • 1970-01-01
    • 2016-02-14
    • 2017-02-18
    • 2020-08-12
    相关资源
    最近更新 更多