我使用Django模型创建了两个表,脚本看起来像这样
我正在使用PostgreSQL 10
生产表:
CREATE TABLE public.foods_food(
id integer NOT NULL DEFAULT nextval('foods_food_id_seq'::regclass),
code character varying(100) COLLATE pg_catalog."default",
product_name character varying(255) COLLATE pg_catalog."default",
brands character varying(255) COLLATE pg_catalog."default",
quantity character varying(255) COLLATE pg_catalog."default",
last_modified_datetime timestamp with time zone NOT NULL,
created_at timestamp with time zone NOT NULL
)
登台表:
CREATE TABLE public.foods_temp(
id integer NOT NULL DEFAULT nextval('foods_temp_id_seq'::regclass),
code character varying(100) COLLATE pg_catalog."default",
product_name character varying(255) COLLATE pg_catalog."default",
)
我将CSV文件复制到登台表,然后尝试使用以下查询将列从登台表复制到生产表。
INSERT INTO foods_food
SELECT * FROM foods_temp;
但是我遇到了这个错误。
ERROR: null value in column "created_at" violates not-null constraint
我可以将created_at
列设置为接受null才能使其起作用,但是我希望在插入条目时自动填充created_at
值。
还有其他方法可以将列复制到生产表并自动插入时间戳吗?
答案 0 :(得分:2)
然后您需要设置默认值:
ALTER TABLE public.foods_food ALTER last_modified_datetime
SET DEFAULT current_timestamp;
ALTER TABLE public.foods_food ALTER created_at
SET DEFAULT current_timestamp;