sqalchemy+ postgresql:施放uuid以进行文字和匹配

发布于 2025-01-23 12:52:04 字数 360 浏览 1 评论 0原文

如何使用运算符的将UUID转换为文本和匹配?例如,我想在sqlalchemy:

SELECT * FROM user
WHERE id::text like '%0c%';

ps:列定义是

from sqlalchemy.dialects.postgresql import UUID
id = Column(
        UUID(as_uuid=True),
        primary_key=True,
        index=True,
        nullable=False,
        default=uuid4,
    )

How can I convert a uuid to text and match using the like operator? E.g I want to do following in sqlalchemy:

SELECT * FROM user
WHERE id::text like '%0c%';

PS: Column definition is

from sqlalchemy.dialects.postgresql import UUID
id = Column(
        UUID(as_uuid=True),
        primary_key=True,
        index=True,
        nullable=False,
        default=uuid4,
    )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天旳寂寞 2025-01-30 12:52:04

使用函数

import sqlalchemy as sa
...
with Session() as s:
    results = s.scalars(
        sa.select(MyModel).where(
            sa.cast(MyModel.id, sa.TEXT).like(f'%{fragment}%')
        )
    )

id :: text in Postgresql是shorthand * cast:

with x as (select gen_random_uuid() as uu)
select uu::text, 
       cast(uu as text), 
       uu::text = cast(uu as text) as "Equals?" from x;
                  uu                  │                  uu                  │ Equals? 
══════════════════════════════════════╪══════════════════════════════════════╪═════════
 b23efe1b-fb05-4d8a-92a3-59339d2ea0f4 │ b23efe1b-fb05-4d8a-92a3-59339d2ea0f4 │ t


*好,主要是...

Use the cast function

import sqlalchemy as sa
...
with Session() as s:
    results = s.scalars(
        sa.select(MyModel).where(
            sa.cast(MyModel.id, sa.TEXT).like(f'%{fragment}%')
        )
    )

id::text in Postgresql is shorthand* for cast:

with x as (select gen_random_uuid() as uu)
select uu::text, 
       cast(uu as text), 
       uu::text = cast(uu as text) as "Equals?" from x;
                  uu                  │                  uu                  │ Equals? 
══════════════════════════════════════╪══════════════════════════════════════╪═════════
 b23efe1b-fb05-4d8a-92a3-59339d2ea0f4 │ b23efe1b-fb05-4d8a-92a3-59339d2ea0f4 │ t


* Well, mostly...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文