Django: "created_at"列中的空值违反了非空约束

标签 django django-models

我正在尝试通过以下代码添加记录:

  Post.objects.update_or_create(
  user=user,
  defaults={
      "title": external_post.get('title'),
      "body": external_post.get('body'),
      "seo": external_post.get('seo')
      }
  )

我已经成功迁移了模型,但出现错误“列“created_at”中的空值违反了非空约束”。
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True) 

最佳答案

我在使用 @transaction atomic 时遇到了同样的问题Django 中的装饰器。基本上我遇到同样错误的原因是我没有在我的一个模型中使用默认的自动增量 ID,而是我使用 primary_key=True 指定了一个特定字段作为主键。

结果,我的数据包含两个相同的主键。这导致了数据库中的“更新”操作而不是“创建”操作。

所以,Django 试图更新一个条目,但 created_at字段丢失,因此出现错误。

我建议你这样做:

post,created = Post.objects.update_or_create(
                   user=user,
                   defaults={
                       "title": external_post.get('title'),
                       "body": external_post.get('body'),
                       "seo": external_post.get('seo')
                    })
if created:
    # your code goes here
    #(this ensures that the code is executed only if an entry is getting created in the database)

您可以阅读本文以获得更好的解释:https://code.djangoproject.com/ticket/17654

关于Django: "created_at"列中的空值违反了非空约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49137484/

相关文章:

python - Django 模型 : Save computed value in a model field

python - 如何在 Django 中反转多个级别的查询对象?

python - 可为空的外键并删除引用的模型实例

使用 Django csrf_exempt View 注册 Android GCM。最佳实践?

javascript - AngularJS + Django : URL refresh or direct access not loading correctly

python - Django QuerySet 用子查询注释

django - App Engine 延迟库中的永久任务失败

django - 在 Django Rest Framework 中将数据作为数组发布

python - 类型错误 : User() got an unexpected keyword argument 'is_staff' when using CustomUser

python - 如何拥有一个包含四个表的 Django 关系数据库?