你可以用
jsonb_array_elements()
将数组扩展到一组
jsonb
然后可以在谓词中使用的元素。通过使用
alias
. 使用诸如
In [4]: class TimeItem(Base):
...: __tablename__ = 'time_item'
...: id = Column(Integer, primary_key=True)
...: start_date_detail = Column(Date)
...: flex = Column(JSONB)
...:
查询可能看起来像
In [39]: session.query(TimeItem).\
...: select_from(TimeItem,
...: func.jsonb_array_elements(TimeItem.flex['communication']).
...: alias('comm')).\
...: filter((TimeItem.start_date_detail +
...: timedelta(seconds=1) *
...: column('comm', type_=JSONB)['remind_date'].
...: astext.
...: cast(Integer)).
...: between(func.now() - timedelta(weeks=1),
...: func.now())).\
...: all()
然后你可以根据你的需要调整谓词,我试着用你的例子来说明。
remind_date
被解释为偏移秒到
start_date_detail
与前一周相比。查询实体时,例如
TimeItem
SQLAlchemy根据对象标识执行自己的重复数据消除,因此查询可以省略SQL端distinct,移动现有子查询表达式中的数组元素,或者类似的操作。