Django: null value in column “created_at” violates not-null constraint
我正在尝试通过以下代码添加记录:
1 2 3 4 5 6 7 8 | 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"中的空值违反了非空约束"。
1 2 | created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) |
当我在Django中使用
结果,我的数据包含两个相同的主键。 这导致数据库中执行"更新"操作而不是"创建"操作。
因此,Django尝试更新条目,但缺少
我建议您改为这样做:
1 2 3 4 5 6 7 8 9 10 | 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