简体   繁体   English

Alembic:将ID字段添加到现有表

[英]alembic: adding id field to existing table

This is a follow on to my previous question . 这是我先前的问题的后续内容。 Basically I have a table that has 2 foreign key links into two other table. 基本上我有一个表,其中有2个外键链接到另外两个表中。 But I think the best way is to add a primary key to the table itself so that it becomes: 但是我认为最好的方法是向表本身添加一个主键,使其变为:

id, int, primary
foreign_id_1, int, primary
foreign_id_2, int, primary

The problem is that there are already a lot of items in the table. 问题在于表中已经有很多项目。 So when I ran alembic upgrade head , it add 0 as the value of all the existing items. 因此,当我运行alembic upgrade head ,它会将所有现有项的值加0 This apparently breaks my code. 这显然破坏了我的代码。

Is there a way to retrospectively add id s to the existing items? 有没有办法向现有项目追溯添加id

You shouldn't have a multiple primary keys in one table. 一个表中不应有多个主键。 See this question. 看到这个问题。 What you want to do? 你想做什么? Perhaps, your problem may be solved with two column index 也许,您的问题可以通过两列索引解决

What you want is not an additional id column as the primary key. 您想要的不是附加的id列作为主键。 What you want instead is to keep your existing composite primary key and add a surrogate id column ( not a primary key column) that auto-increments to keeps track of the order of insertion. 相反,您要保留现有的组合主键,并添加一个代理id列( 而非主键列),该列会自动递增以跟踪插入顺序。 But because you've already inserted all your rows into the table, you've lost the order, so it makes no sense to "recover" that order. 但是,由于您已经将所有行插入到表中,因此丢失了该顺序,因此“恢复”该顺序没有任何意义。 You can simply assign 0 to that column without issue. 您可以简单地将0分配给该列而不会出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM