【问题标题】:Filter query in SQLAlchemy with date and hybrid_property使用日期和混合属性在 SQLAlchemy 中过滤查询
【发布时间】:2014-08-01 15:36:57
【问题描述】:

我有一个包含 year_id、month_id 和 day_id 列的数据库表(都是 NUMBER)。我想做一个过滤日期的查询。为了简化它,我想添加 hybrid_property 以将提到的字段一起加入到日期中。

class MyModel(Base):
    __table__ = Base.metadata.tables['some_table']
    @hybrid_property
    def created_on(self):
        return date(self.year_id, self.month_id, self.day_id)

但是当我查询时

session.query(MyModel).filter(MyModel.created_on==date(2010, 2, 2))

我收到一个错误TypeError: an integer is required (got type InstrumentedAttribute)

是否有另一种方法进行此类过滤:我无法修改数据库架构(因此字段应保持不变),但同时很难将日期与 3 个单独的列进行比较?

【问题讨论】:

  • 如果你能做到,我建议在数据库上创建一个计算列,其值为DATE。我不确定其他 RDBMS,但在 MSSQL 中,您甚至可以保留计算列并在其上创建索引。您还需要相应地为 SA 配置此列(请参阅docs.sqlalchemy.org/en/latest/core/…)。

标签: python sql sqlalchemy


【解决方案1】:

您需要向混合属性添加一个表达式,但根据您的 RDBMS,它可能会有所不同。请参阅下面的 sqlite 示例:

@hybrid_property
def created_on(self):
    return date(self.year_id, self.month_id, self.day_id)

@created_on.expression
def created_on(cls):
    # @todo: create RDBMS-specific fucntion
    # return func.date(cls.year_id, cls.month_id, cls.day_id)

    # below works on Sqlite: format to YYYY-MM-DD
    return (func.cast(cls.year_id, String) + '-' +
            func.substr('0' + func.cast(cls.month_id, String), -2) + '-' +
            func.substr('0' + func.cast(cls.day_id, String), -2))

【讨论】:

  • 亲爱的,请改进答案 - 如果您知道的话,请简化 sqlite 的日期转换。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-01-08
  • 2021-01-24
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
相关资源
最近更新 更多