【问题标题】:Postgre/SQLAlchemy UUID inserts but failed to comparePostgre/SQLAlchemy UUID 插入但无法比较
【发布时间】:2013-11-22 22:37:01
【问题描述】:

我正在使用 SQLAlchemy 模型访问 Postgre 数据库。在其中一个模型中,我有 UUID 类型的 Column。

id = Column(UUID(as_uuid=True), default=uuid.uuid4(), nullable=False, unique=True)

当我尝试插入新行(生成新 id)时它会起作用。 问题是当我尝试通过 id 获取 Person 时,我尝试喜欢

person = session.query(Person).filter(Person.id.like(some_id)).first()

some_id 是从客户端收到的字符串 但后来我得到error LIKE (Programming Error) operator does not exist: uuid ~~ unknown。

如何通过 SQLAlchemy 获取/比较数据库中的 UUID 列?

【问题讨论】:

  • 您确定您的 uuid 是唯一的吗?因为据我所知,您应该省略 default: default=uuid.uuid4 中的大括号。
  • @javex:非常好的观点。另外,将like 与uuid 一起使用真的有意义吗?为什么不只是.filter(Person.id==some_guid).first() 甚至session.query(Person).get(some_guid)?
  • @van 我从客户端字符串中获取,我需要在数据库中找到具有相同 ID 的人,我尝试使用 == 但 id 不起作用。当我使用 mysql 时,liek 可以工作,但我想切换到 postgre,比如我正在使用的docs.sqlalchemy.org/en/rel_0_9/core/types.html GUID(也尝试使用 postgre 基本方言)

标签: python postgresql sqlalchemy uuid


【解决方案1】:

不要使用 like,使用 =,而不是 ==(在 ISO 标准 SQL 中,= 表示相等)。

请记住,UUID 在 PostgreSQL 中存储为二进制类型,而不是文本字符串,因此LIKE 没有任何意义。您可能可以使用uuid::text LIKE ?,但它在大型集合上的表现会很差,因为您有效地确保不能使用索引。

但= 有效,而且更可取:

mydb=>select 'd796d940-687f-11e3-bbb6-88ae1de492b9'::uuid = 'd796d940-687f-11e3-bbb6-88ae1de492b9';
 ?column? 
----------
 t
(1 row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-03
    • 2014-05-13
    • 1970-01-01
    • 2022-01-27
    • 2018-12-30
    • 2017-05-31
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多