【问题标题】:psycopg2.errors.UndefinedFunction operator does not exist: uuid = textpsycopg2.errors.UndefinedFunction 运算符不存在:uuid = text
【发布时间】:2022-01-19 16:45:44
【问题描述】:

我正在使用带有 Postgres 数据库的烧瓶 Sqlalchemy,我正在尝试过滤以查找模型的所有实例,其中 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.

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    错误消息告诉您 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))
    

    【讨论】:

      猜你喜欢
      • 2019-11-12
      • 2022-10-15
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      相关资源
      最近更新 更多