我已经为一个烧瓶项目建立了一个postgresql数据库。我的项目中有一个布尔类型的列ticked
。当我尝试写入数据库时。这是我得到的错误: column "ticked" is of type boolean but expression is of type integer
确实,我正在尝试使用整数值创建我的记录:1
。但是,这在我的同事环境中非常有效。我首先认为这是因为我没有在 psql 最新版本上运行,但我将 psql 更新到版本 10.1,但我仍然遇到这个问题。
我们使用 sqlalchemy 来生成表。以下是与有问题的列相关的模型:
class Email(db.Model):
__tablename__ = "emails"
email = db.Column(db.String(254), primary_key=True)
ticked = db.Column(db.Boolean(), nullable=False)
primary = db.Column(db.Boolean(), nullable=False)
你知道为什么 psql 不接受布尔字段的 0 或 1 值吗?
你需要正确转换它们:
t=# select 1::boolean, 0::boolean;
bool | bool
------+------
t | f
(1 row)
或与 SQL 兼容:
t=# select cast (1 as boolean), cast (0 as boolean);
bool | bool
------+------
t | f
(1 row)
或其他帖子特定:
t=# select boolean '1', boolean '0';
bool | bool
------+------
t | f
(1 row)
还有隐式的文本转换为布尔值:
t=# create table b(v boolean);
CREATE TABLE
t=# insert into b values ('0');
INSERT 0 1
t=# select * from b;
v
---
f
(1 row)
问题不是psql的版本,而是我的sqlAlchemy版本。我是 1.1.13,现在我已经升级到 1.2.1 我不再有错误