【问题标题】:SQLAlchemy: filter by datetime in JSON fieldSQLAlchemy:在 JSON 字段中按日期时间过滤
【发布时间】:2019-09-29 23:09:19
【问题描述】:

我需要根据 JSON DB 字段 (postgres) 中的日期过滤查询。

E. G。对于整数比较,此语法有效:

r = Customer.query.filter(Customer.jsondata[('basic', 'age')].astext.cast(Integer) > 18).all()

但是对于不超过 12 个月的 iso 格式的日期时间,此查询如何工作:

r = Customer.query.filter(Customer.jsondata[('basic', 'dateCreated')].astext.cast(???) > comparison_value).all()

我需要投射什么?

比较值可以是什么类型?

我的想法是正确的概念吗?

感谢任何帮助!

【问题讨论】:

  • 首先使用普通的 SQL,一旦你知道它正在工作,然后现在是时候弄清楚如何使用 SQLAlchemy 的功能获取该 SQL。但假设您有与其他类型完全相同的查询,那么我会尝试转换为 DateTime...

标签: python sqlalchemy


【解决方案1】:

感谢 ThiefMaster 的评论,解决方案非常简单。

我用过:

from sqlalchemy.types import DateTime
import pendulum

r = Customer.query.filter(
      Customer.custcontext_json[('basic', 'dateCreated')].astext.cast(DateTime) > pendulum.now('UTC').subtract(months= 12)
      ).all()

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 2019-04-15
    • 1970-01-01
    • 2012-02-12
    • 2015-03-06
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多