Postgre / SQLAlchemy UUID插入但无法比较

时间:2013-11-22 22:37:02

标签: python postgresql sqlalchemy uuid

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

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列?

1 个答案:

答案 0 :(得分:0)

使用=,而不是==(在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)