【问题标题】:Django: null value in column "created_at" violates not-null constraintDjango:“created_at”列中的空值违反非空约束
【发布时间】:2018-08-14 16:52:56
【问题描述】:

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

  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) 

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我在 Django 中使用 @transaction atomic 装饰器时遇到了同样的问题。基本上我遇到同样错误的原因是我没有在我的一个模型中使用默认的自动增量 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

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2018-05-28
      • 2021-03-30
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      相关资源
      最近更新 更多