6

我目前的 Django 应用程序陷入了第 22 条问题。当我从 UUID 移动到普通的旧 ID 时,我必须将列的类型从 Varying char 更改为 Integer(数据不会因为它的物理常数而改变)。现在 django 最初抛出了一个关于无法从 VarChar 转换为 Int 的 Fit,所以我“帮助”了它:

 ALTER TABLE glass_fill ALTER COLUMN id TYPE INTEGER USING CAST(id AS INT);

现在,它说:

django.db.utils.DatabaseError: foreign key constraint "glass_fill_manufacturer_glass_fill_id_fkey" cannot be implemented
DETAIL:  Key columns "glass_fill_id" and "id" are of incompatible types: integer and character varying.

有任何想法吗?

注意:glass_fill_manufacturer 表尚未创建,django 尝试在 syncdb 上但失败。还有,

ALTER TABLE glass_fill ALTER COLUMN id TYPE INTEGER USING CAST(id AS INT); 

行并没有像我想的那样改变列。

glass_fill 表架构:

-- Table: glass_fill

-- DROP TABLE glass_fill;

CREATE TABLE glass_fill
(
  id character varying(36) NOT NULL,
  name character varying(255),
  temperature real,
  density real,
  viscosity real,
  conductivity real,
  heat_capacity real,
  colour text,
  CONSTRAINT glass_fill_pkey PRIMARY KEY (id )
)
WITH (
  OIDS=FALSE
);
4

2 回答 2

12
ALTER TABLE glass_fill_manufacturer 
ALTER COLUMN glass_fill_id TYPE INTEGER USING CAST(glass_fill_id AS INT)
;

我猜从你的文字来看,Django 会以某种方式做到这一点,但如果它没有:

ALTER TABLE glass_fill_manufacturer 
drop constraint glass_fill_manufacturer_glass_fill_id_fkey
;

alter table glass_fill_manufacturer 
ADD constraint glass_fill_manufacturer_glass_fill_id_fkey 
foreign key (glass_fill_id) references glass_fill (id)
;
于 2012-05-25T11:30:52.650 回答
0

您应该执行以下操作:

  1. 放弃约束
  2. 创建一个临时表来保存新旧 id 之间的映射
  3. 更新glass_fill,将值返回到临时表中
  4. 从临时表更新引用表
  5. 更改所有表上的列类型
  6. 重新创建约束
于 2012-05-25T11:25:00.173 回答