【问题标题】:django: IntegrityError: duplicate key value violates unique constraintdjango:IntegrityError:重复键值违反唯一约束
【发布时间】:2013-06-23 17:55:06
【问题描述】:

当我尝试将新条目保存到名为“config”的表中时遇到了这个问题,

class Config(models.Model):
    ident = models.CharField(max_length=uuidLength, null=True, editable=False)
    scanner = models.ForeignKey('Scanner')
    name = models.CharField(max_length=64)
   ''' some other fields '''

而 postgres 给出了这样的错误(应用程序被称为“pegasus”,所以 django 给出的表名实际上是“pegasus_config”):

IntegrityError: duplicate key value violates unique constraint "pegasus_config_scanner_id_name_key"
DETAIL:  Key (scanner_id, name)=(2, ) already exists.

我在stackoverflow中搜索,找到this的解决方案,问题是我不知道我应该重置哪个表的索引。 我根据答案做了以下操作:

SELECT setval('pegasus_config_id_seq', (SELECT MAX(id) FROM pegasus_config)+1)

但问题仍然存在。我还进入了数据库,发现“pegasus_config_scanner_id_name_key”实际上是一个索引。所以我对重置哪个索引感到困惑?请帮忙。谢谢。

【问题讨论】:

  • 我认为您应该删除该索引。在我看来,该表将scanner_idname 字段作为键。这是你想要的吗?

标签: django postgresql database-integrity


【解决方案1】:

您可以尝试如下查询以确定哪个表定义了该唯一约束:

SELECT  n.nspname as schema_name,
        co.conrelid::regclass as table_name,
        co.conname as constraint_name,
        pg_catalog.pg_get_constraintdef(co.oid, true) as constraing_def
FROM pg_constraint co
INNER JOIN pg_catalog.pg_class cl ON cl.oid = co.conrelid
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = cl.relnamespace
WHERE co.conname = 'pegasus_config_scanner_id_name_key'
AND co.contype = 'u'

【讨论】:

  • 另请注意,如果受约束列中的值之一为 NULL,则在定义为 NOT NULL 的列上定义的 UNIQUE 约束/索引可能具有重复条目。我并不是说这是这里的问题,但是当我在约束违规(“名称”列)中看到 NULL 时想到了它。
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 2020-03-27
  • 2016-06-12
  • 2013-03-15
  • 2016-11-27
  • 2018-03-14
  • 2016-09-27
  • 2019-07-22
相关资源
最近更新 更多