psycopg2.errors.UndefinedFunction 运算符不存在:uuid = text

psycopg2.errors.UndefinedFunction operator does not exist: uuid = text

我将 flask Sqlalchemy 与 Postgres 数据库一起使用,我正在尝试过滤以查找模型的所有实例,其中 json 数据列的 1 个字符串值等于另一个 (UUID4)列。

class MyModel (db.Model):
id = db.Column(UUID(as_uuid=True), primary_key=True,
                   index=True, unique=True, nullable=False,
                   server_default=sa_text("uuid_generate_v4()"))
site = db.Column(UUID(as_uuid=True), db.ForeignKey(
        'site.id'), index=True, nullable=False)
data = db.Column(JSON, default={}, nullable=False)

这些模型的数据栏看起来像

{
    "cluster": "198519a5-b04a-4371-b188-2b992c25d0ae",
    "status": "Pending"
}

这就是我正在尝试的:

filteredModels = MyModel.query.filter(MyModel.site == MyModel.data['cluster'].astext)

我得到:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: uuid = text
LINE 4: ...sset.type = 'testplan' AND site_static_asset.site = (site_st...
                                                             

HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

错误消息告诉您 Postgresql 无法直接比较 UUID 与文本值。也就是说无法处理

MyModel.site == MyModel.data['cluster'].astext

要解决此问题,您需要 cast 比较的一侧与另一侧的类型相同。这些都应该有效:

from sqlalchemy import cast, String

MyModel.query.filter(cast(MyModel.site, String) == MyModel.data['cluster'].astext)

MyModel.query.filter(MyModel.site == cast(MyModel.data['cluster'].astext, UUID))