当值的一列仅包含Null
个值时,需要帮助解决问题。示例:
create table foo (
id serial constraint foo_pk primary key,
a int,
b int
);
insert into foo (a,b) values (1, 1), (2, 2);
update foo t
set a = v.a, b = v.b
from (values (1, NULL, 1),(2, NULL, 2)) as v(id, a, b)
where v.id = t.id;
这给了我
[42804] ERROR: column "a" is of type integer but expression is of type text
Hint: You will need to rewrite or cast the expression. Position: 22
我正在使用psycopg2.extras.execute_values
来更新多个Django ORM对象。寻找不需要将null显式转换为字段类型的解决方案。
答案 0 :(得分:0)
由于您为列a
传递的所有值都是NULL
s,因此Postgres将隐式认为它们是TEXT
s
您有2个选项,
在a
表达式中将SET
的值转换为int。
set a = v.a::int
OR
广播a
到INT
的值之一,其他值默认为。
values (1, NULL::int, 1),(2, NULL, 2)) as v(id, a, b)