python - Sqlalchemy 无法将 jsonb 转换为 bool 值

标签 python casting sqlalchemy

我从模型中提取了以下值,并尝试将其转换为 bool 值。但是,当我运行该程序时,我收到一条错误消息,指出“无法将 jsonb 类型转换为 bool 值。这里jsonb值的值是boolean,那为什么不能强制转换呢?我需要更改什么?

我要获取的数据值是 {"unsubscribe": "True"} 的 bool 值

这是导致错误的行。

args.append(Customer.data['unsubscribed'].cast(sqlalchemy.Boolean) == "{}".format(True))

这是客户模型

class Customer(Base):
    __tablename__ = 'customers'
    id = Column(UUID, primary_key=True, server_default='uuid_generate_v4()')
    phone_number = Column(String)
    data = Column(JSONB)
    created_at = Column(DateTime, server_default='NOW()')
    updated_at = Column(DateTime, server_default='NOW()')

    @property
    def agent_number(self):
        return self.data["agent"]["phoneNumber"]

    def __repr__(self):
        return '<Customer(id={}, phone_number={}, data={}, created_at={}, updated_at={})>'.format(
            self.id,
            self.phone_number,
            self.data,
            self.created_at,
            self.updated_at
        )

最佳答案

就PostgreSQL而言,true是一个jsonb类型,不是SQL的boolean类型。你做不到

SELECT 'true'::jsonb::boolean;

你也做不到

SELECT '123'::jsonb::int;

您需要进行某种转换。一种方法是使用 ->> 转换为 varchar:

SELECT (('{"unsubscribed": true}'::jsonb)->>'unsubscribed')::boolean;

或者,您可以使用 jsonb_to_record :

SELECT unsubscribed FROM jsonb_to_record('{"unsubscribed": true}'::jsonb) AS o(unsubscribed boolean);

就SQLAlchemy而言,你可以做到

Customer.data['unsubscribed'].astext.cast(sqlalchemy.Boolean).is_(True)

或者,走另一条路

Customer.data['unsubscribed'] == cast('true', JSONB)

关于python - Sqlalchemy 无法将 jsonb 转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44957367/

相关文章:

C 指针 - 交换

netbeans - PHP/Symfony/Netbeans 中类变量的类型转换

python - 如何从 SqlAlchemy 中的多对多集合中删除所有项目?

python - SQLALchemy:根据列键/名称获取行元素

python - SQLAlchemy 和多个数据库

python - 在从另一个用 C 实现的类驱动的类上使用元类

python - Django 日志记录请求

python - 通过线性回归进行 tensorflow 图像分割

Python 字典和多个 dict[]

java - 从父类(super class)型转换回子类型