English 中文(简体)
如何在 PostgreSQL 中更改列类型和所有外国密钥?
原标题:How to change column type and all foreign keys in PostgreSQL?

我目前被Django应用程序困在22号渔获物中。我必须改变专栏的类型,从变种字符改为 Integer,因为i m 正在从 UUIDs 移动到普通的旧的IDs(数据从未改变,因为它是物理常数 ) 。 现在, 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.

有什么想法吗?

注意: 玻璃_ fill_ manucacturer Table 尚未创建, 但 Django 试图在同步上尝试, 但失败了 。

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

线条没有如我想的那样更改列。

玻璃杯表图案:

-- 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
);
最佳回答
ALTER TABLE glass_fill_manufacturer 
ALTER COLUMN glass_fill_id TYPE INTEGER USING CAST(glass_fill_id AS INT)
;

我猜通过你的短信 决哥会不知怎么做到 但如果不做到的话

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)
;
问题回答

您应该采取以下行动:

  1. Drop the constraints
  2. Create a temporary table to hold mapping between old and new ids
  3. Update glass_fill, returning the values into the temporary table
  4. Update the referencing tables from the temporary table
  5. Alter column types on all tables
  6. Recreate the constraints




相关问题
摘录数据

我如何将Excel板的数据输入我的Django应用? I m将PosgreSQL数据库作为数据库。

Postgres dump of only parts of tables for a dev snapshot

On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 ...

How to join attributes in sql select statement?

I want to join few attributes in select statement as one for example select id, (name + + surname + + age) as info from users this doesn t work, how to do it? I m using postgreSQL.

What text encoding to use?

I need to setup my PostgreSQL DB s text encoding to handle non-American English characters that you d find showing up in languages such as German, Spanish, and French. What character encoding should ...

SQL LIKE condition to check for integer?

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A": SELECT * ...

热门标签