You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将int转为BigInteger?Sqlalchemy类型匹配问题

解决Python中Sqlalchemy ORM与PostgreSQL bigint字段的类型匹配问题

问题本质

你碰到的asyncpg.exceptions.UndefinedFunctionError: operator does not exist: bigint !~~* unknown错误,核心是类型不匹配:你使用了字符串模糊匹配操作(!~~*是PostgreSQL的不区分大小写模糊匹配运算符),但操作的一方是bigint类型字段,另一方是未正确转换的类型,导致数据库找不到对应运算符。

具体解决方案

Python的int无需手动转BigInteger,Sqlalchemy会自动处理类型映射,重点是保证查询操作的类型逻辑正确:

1. 确认模型字段定义无误

先检查你的Sqlalchemy模型里,telegram_id必须定义为BigInteger类型:

from sqlalchemy import BigInteger, Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    telegram_id = Column(BigInteger, nullable=False, unique=True)  # 此处必须用BigInteger

2. 常规查询直接用Python int

Python的int可以直接和Sqlalchemy的BigInteger字段做相等比较,无需额外转换:

# 正确的相等匹配查询
user = await db_session.query(User).filter(User.telegram_id == 1234567890).first()

3. 模糊查询需先转字符串

bigint类型不支持直接模糊查询,必须先把字段转成字符串再操作,这是你报错的关键原因:

from sqlalchemy import cast, String
# 正确的模糊查询方式:将bigint字段转为字符串后匹配
user = await db_session.query(User).filter(cast(User.telegram_id, String).ilike("%123%")).first()

4. 特殊场景强制类型转换

如果遇到极端情况需要手动指定类型,可使用Sqlalchemy的cast函数:

from sqlalchemy import cast, BigInteger
# 强制将Python int转为BigInteger类型进行匹配
user = await db_session.query(User).filter(User.telegram_id == cast(1234567890, BigInteger)).first()

关键提示

  • PostgreSQL的bigint与Sqlalchemy的BigInteger对应,Python的int可以直接兼容,不需要手动做类型转换。
  • 模糊查询属于字符串操作,不能直接作用于数值类型字段,必须先做类型转换。

内容的提问来源于stack exchange,提问作者Benjamin Button

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:09:30