我有一个现有的数据库表。 我想向其中添加一个新的 (Char) 字段。该字段将具有唯一值。
当我尝试这样做时:
id = models.CharField(max_length=100, Unique=True)
我收到完整性错误。
我尝试过的其他一些事情:
id = models.CharField(max_length=100, Unique=True,
default="".join([random.random(), random.random()])))
和
id = models.CharField(max_length=100,
default="".join([random.random(), random.random()])))
同样的错误。
有解决办法吗?
最佳答案
我将显示以下内容,新列是 INT 而不是 CHAR。一样的区别。
create table t1
( id int auto_increment primary key,
col1 varchar(100) not null
);
insert t1(col1) values ('fish'),('apple'),('frog');
alter table t1 add column col2 int; -- OK (all of col2 is now NULL)
ALTER TABLE t1 ADD UNIQUE (col2); -- OK (now a UNIQUE constraint on col2)
show create table t1;
CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`col1` varchar(100) NOT NULL,
`col2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `col2` (`col2`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
现在让我们重新开始,看看它会爆炸。
drop table t1;
create table t1
( id int auto_increment primary key,
col1 varchar(100) not null
);
insert t1(col1) values ('fish'),('apple'),('frog');
alter table t1 add column col2 int not null; -- OK (at the moment)
-- note: (all of col2 is now 0)
ALTER TABLE t1 ADD UNIQUE (col2); -- error 1062 duplicate entry '0' for key 'col2'
上述失败的原因是因为 col2 添加列上的 NOT NULL 使所有数据都为 0。然后 UNIQUE 约束尝试失败。
下面我们继续思路:
drop table t1;
create table t1
( id int auto_increment primary key,
col1 varchar(100) not null
);
insert t1(col1) values ('fish'),('apple'),('frog');
alter table t1 add column col2 int; -- OK (all of col2 is now NULL)
ALTER TABLE t1 ADD UNIQUE (col2); -- OK
select * from t1; -- col2 is NULL for all 3 rows
update t1 set col2=7 where id=1; -- OK
update t1 set col2=7 where id=2; -- error 1062 duplicate entry '7' for key 'col2'
这个故事的寓意是,如果您将一列添加到一个已有数据的表中,并且希望该新列是唯一的,您需要先让它可以为空。然后创建唯一约束。现在所有数据都是 NULL,所以唯一约束是宽容的。但是一旦您将数据调整为非 NULL,它最好是唯一的。调整意味着更新或插入。因此 col2 之后需要保持为 NULL 或 UNIQUE。
关于python - 在具有现有值的现有数据库表中添加新的唯一字段 - Django1.7/MySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071295/