【问题标题】:TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute类型错误:timedelta 微秒组件不支持的类型:InstrumentedAttribute
【发布时间】:2022-12-05 01:33:44
【问题描述】:

我在执行此任务时也遇到错误。

模型.py

云图大师

created_tmstmp = Column(DateTime(), default = datetime.now(timezone.utc))

客户主管

ttl = Column(BigInteger, nullable=False)

询问:-

db.query(CloudImageMaster).join(ClientMaster).filter(
    (
    CloudImageMaster.created_tmstmp + timedelta(microseconds=ClientMaster.ttl)
    ) < today
).all()

错误信息 :-

TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute

我在上面试过了。它应该按照代码工作。我在这方面做错了什么。

【问题讨论】:

  • 你能再解释一下吗?如果你能写出正确的陈述。
  • 我们正在使用 Postgresql

标签: python python-3.x postgresql sqlalchemy fastapi


【解决方案1】:

给定一个像MyMode.attr == something 这样的过滤器表达式,左侧 (LHS) 可以被认为属于数据库端,右侧 (RHS) 属于应用程序。这意味着 RHS 必须用 SQLAlchemy 认为的数据库结构(ORM 实体、表、列、数据库函数)来表示,而 LHS 则用普通的 Python 代码来表示。

这意味着我们不能从 Datetime 列(数据库构造)中减去 timedelta(Python 构造);我们必须将 timedelta 转换为数据库构造 - PostgreSQL 间隔。我们可以通过使用 make_interval 函数来做到这一点,将 ttl 除以 1000,因为 make_interval 不接受微秒参数。

from sqlalchemy import func

db.query(CloudImageMaster)
  .join(ClientMaster)
  .filter(
      (
          CloudImageMaster.created_tmstmp
          + func.make_interval(0, 0, 0, 0, 0, 0, ClientMaster.ttl /1000)
      ) < today
  ).all()

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多