SqlAlchemy 添加混合属性,该属性是日期时间和数字字段的总和

问题描述 投票:0回答:1

我正在尝试计算结合 SQLAlchemy 模型中两个现有字段的字段,并在查询参数中使用它。

我有一个这样的模型:

    class Booking(BaseORMModel):
      start: Mapped[datetime] = mapped_column(TIMESTAMP(timezone=True))
      minutes: duration_minutes: Mapped[int] = mapped_column(Numeric)

我想动态计算结束作为

start
minutes
的总和。这是我的尝试:

    class Booking(BaseORMModel):
      ...
      @hybrid_property
    def ended_at(self):
        return self.scheduled_at + timedelta(minutes=self.duration_minutes)

    @ended_at.expression
    def ended_at(cls):
        duration_interval = func.cast(concat(cls.duration_minutes, ' MINUTES'), INTERVAL)
        ended_at = func.sum(cls.scheduled_at + duration_interval)
        return ended_at

这是我的询问

query = query.where(Booking.ended_at < now)

这就是我得到的:

sqlalchemy.exc.ProgrammingError: (psycopg.errors.UndefinedFunction) function sum(timestamp with time zone) does not exist
python sqlalchemy
1个回答
0
投票

这样解决:

@ended_at.expression  # type: ignore[no-redef]
    def ended_at(cls):
        casted_duration = func.cast(cls.duration_minutes, Integer)
        # make_interval params: (years, months, weeks, days, hours, minutes, seconds)
        interval = func.make_interval(0, 0, 0, 0, 0, casted_duration)
        ended_at = cls.scheduled_at + interval
        return ended_at
© www.soinside.com 2019 - 2024. All rights reserved.