1

I currently have this:

class Committee(models.Model):
    # ...some fields...
    committee_xml_id = models.IntegerField()

I need to make the field committee_xml_id unique, i.e. make it so:

class Committee(models.Model):
    # ...some fields...
    committee_xml_id = models.IntegerField(unique=True)

I have also tried making it so:

class Committee(models.Model):
    # ...some fields...
    committee_xml_id = models.IntegerField(unique=True, db_index=False)

Alas, the result is the same.

Having run ./manage.py makemigrations and subsequently, ./manage.py migrate, the problem is this:

django.db.utils.OperationalError: (1061, "Duplicate key name 'appname_committee_committee_xml_id_d1210032_uniq'")

At first glance, it seems like the problem is that there is already non-unique data in the table, but the problem is precisely that there isn't. There are only 45 rows in the table, and the field committee_xml_id contains only unique entries.

The following query gives no results, as expected when there are no duplicates:

SELECT
    com.committee_xml_id,
    COUNT(*)
FROM
    appname_committee AS com
GROUP BY
    com.committee_xml_id
HAVING
    COUNT(*) != 1

For rigor, here is the same query without the HAVING-condition, showing clearly that there are indeed no duplicates:

SELECT
    com.committee_xml_id,
    COUNT(*)
FROM
    appname_committee AS com
GROUP BY
    com.committee_xml_id

Result is:

# committee_xml_id, COUNT(*)
78, 1
79, 1
124, 1
125, 1
129, 1
130, 1
131, 1
132, 1
133, 1
134, 1
137, 1
139, 1
140, 1
141, 1
142, 1
147, 1
148, 1
149, 1
150, 1
151, 1
152, 1
153, 1
154, 1
160, 1
166, 1
167, 1
168, 1
169, 1
170, 1
176, 1
192, 1
193, 1
194, 1
195, 1
198, 1
199, 1
200, 1
201, 1
202, 1
203, 1
204, 1
205, 1
206, 1
207, 1
216, 1

Any help greatly appreciated.

4

1 回答 1

3

错误与表中的数据无关。如果我们试图插入违反唯一约束的数据,或者如果我们试图在表中有重复项时定义一个唯一键,我们会看到一个不同的错误:

错误代码 1062:重复条目...


1061我们尝试定义一个新键并且该键已经存在时,就会发生错误。

作为演示:

  create table foo2 (id int);

  0 row(s) affected

  insert into foo2 (id) values (1),(1);

  2 row(s) affected

  alter table foo2 add unique key foo2_ux1 (id);

错误代码:1062 键 'foo2_ux1' 的重复条目 '1'

  alter table foo2 add key foo2_ix2 (id);

  0 row(s) affected

  alter table foo2 add key foo2_ix2 (id);

错误代码:1061 重复键名“foo2_ix2”

  alter table foo2 add UNIQUE key foo2_ix2 (id);

错误代码:1061 重复键名“foo2_ix2”

遗嘱向SHOW CREATE TABLE我们展示了该名称的密钥实际上已经存在

  CREATE TABLE `foo2` (
  `id` INT(11) DEFAULT NULL,
  KEY `foo2_ix2` (`id`)
  ) ENGINE=InnoDB
于 2017-11-09T01:51:53.620 回答