我正在使用 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 是从客户端收到的字符串
但随后我得到了 错误 LIKE (Programming Error) operator does not exist: uuid ~~ unknown
.
如何通过 SQLAlchemy 获取/比较数据库中的 UUID 列?
最佳答案
不要使用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)
关于python - Postgre/SQLAlchemy UUID 插入但无法比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20155805/