Django Import-Export导入重复键值违反错误 [英] Django Import-Export Import Duplicate key value violates Error

查看:407
本文介绍了Django Import-Export导入重复键值违反错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.10,Python 3.6和PostgreSQL作为数据库后端的项目,其中有一个名为 Article的模型,我需要从CSV文件导入数据。我已经导入了我的第一个CSV文件成功使用以下字段:
id,link& category
它的ID字段从1到1960
,然后在下一个文件中,我从1961年起开始使用ID字段,但它显示了以下错误:

I'm working on a project with Django 1.10, Python 3.6 and PostgreSQL as the database backend, in which I have a model called 'Article" and I need to import data from CSV files. I have imported my first CSV file successfully with the following fields: id, link & category It's ID fields starts from 1 to 1960 then in next file, I have started ID field from 1961 to onward but it shows the following error:


行号:1961-重复的键值违反了唯一约束 article_article_pkey详情:键(id)=(1961)已经

Line number: 1961 - duplicate key value violates unique constraint "article_article_pkey" DETAIL: Key (id)=(1961) already exists.

即使我在Django admin中看到我的Article模型,它也显示了从1到1960年的ID

Even when i see my Article model in Django admin it shows IDs from 1- 1960

这是我的模型。

class Article(models.Model):
   id = models.AutoField(primary_key=True)
   link = models.URLField(max_length=255)
   category = models.CharField(max_length=255, choices=Categories)

这里是admin.py

@admin.register(Article)
    class ArticleAdmin(ImportExportModelAdmin):
    resource_class = views.ArticleResource
    readonly_fields = ('id',)


推荐答案

我已经触发了问题所在:
实际上,问题是PostgreSQL主键不与表行同步的顺序。
这就是为什么,当我插入新行时,我得到一个重复的键错误,因为串行数据类型中隐含的序列返回了一个已经存在的数字。

I have triggered that what's the issue : Actually, the problem is PostgreSQL primary key sequential which is not synced with table rows. That's why, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.

To解决此问题,我们必须重置PostgreSQL的ID顺序,
这是逐步指南:

To solve this issue we have to reset the ID sequential for PostgreSQL, Here's the step by step guide:


  1. 登录到数据库外壳并连接到数据库

  2. 首先,检查表ID列的最大值,如下所示:从your_table中选择MAX(id);

  3. 然后,检查ID的下一个值是什么: SELECT nextval('your_table_id_seq');

  4. 如果nextval是下一个最大值,那么它是正确的。 例如MAX = 10& nextval = 11

  5. 否则将表的id_seq重置为:

  1. Log onto the DB shell and connect to your database
  2. First, check maximum value for id column of your table as SELECT MAX(id) FROM your_table;
  3. Then, check what's going to be the next value for ID as : SELECT nextval('your_table_id_seq');
  4. If nextval is the next number of Max value then it's right. e.g MAX=10 & nextval=11
  5. Otherwise reset the id_seq for your table as:

BEGIN;

-在更新计数器时防止并发插入

-- protect against concurrent inserts while you update the counter

在独占模式下锁定表your_table;

-更新序列

SELECT setval('your_table_id_seq',COALESCE((SELECT MAX(id)+1 from your_table),1),false);

COMMIT;

这篇关于Django Import-Export导入重复键值违反错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆